c# – 无法下载文件

我正在尝试从C#应用程序下载文件.我尝试了两种不同的方法,但两者都产生相同的响应:

“远程服务器返回错误:(401)未经授权.”

我很确定这是凭证问题(因为401).如果我从浏览器导航到该URL并输入所提供的相同凭据,则该文件下载得很好.在“尝试2”(下面)中,对于authtype,我尝试过:
NTLM,Basic,Negotiate和Digest没有任何运气.

有谁看到我在这里做错了什么?

谢谢您的帮助!

尝试1:

string username = "username";
string password = "password";
string domain = "domain";
string url = @"http://LiveLinkInstance.com/livelink/llisapi.dll/999999/WordDocument.docx?func=doc.Fetch&nodeid=999999&ReadOnly=True&VerNum=-2&nexturl=/livelink/llisapi.dll?func=ll&objId=888888&objAction=browse&viewType=1";  

// Create an instance of WebClient
WebClient client = new WebClient();
client.Proxy = null;

client.Credentials = new System.Net.NetworkCredential(username, password, domain);

client.DownloadFile(new Uri(url), @"C:\FileDownloads\test.txt");

尝试2:

string username = "username";
string password = "password";
string domain = "domain";
string url = @"http://LiveLinkInstance.com/livelink/llisapi.dll/999999/WordDocument.docx?func=doc.Fetch&nodeid=999999&ReadOnly=True&VerNum=-2&nexturl=/livelink/llisapi.dll?func=ll&objId=888888&objAction=browse&viewType=1";

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(domain + "\\" + username + ":" + password));
wr.Headers.Add("Authorization", "Basic " + credentials);

CredentialCache cc = new CredentialCache();
cc.Add(new Uri(url), "NTLM", new NetworkCredential(username, password, domain));
wr.Credentials = cc;
Stream str = ws.GetResponseStream();

最佳答案 正如Amitay所说,使用fiddler来比较来自浏览器的流量是最好的方法.顺便说一句,在SO上看
here – OP的情况是,请求被重定向到不同的位置,但凭证没有重新通过.所以OP做了手动重定向来解决这个问题.

点赞