我可以使用浏览器中的以下链接成功下载文件:
现在我需要在我的C#应用程序中执行此操作。
解决方案1 :使用WebClient
string url = $"https://assoc-datafeeds-na.amazon.com/datafeed/getReport?filename=feedreport-1265.xml.gz";
using (var webClient = new WebClient())
{
string authInfo =Convert.ToBase64String(Encoding.Default.GetBytes("userbob:qwerty"));
webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + authInfo;
webClient.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
webClient.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
var data = webClient.DownloadData(url);
}
DownloadData抛出异常:远程服务器返回错误:(500)内部服务器错误。
解决方案2:使用WebRequest
var request = WebRequest.Create(url);
string authInfo =Convert.ToBase64String(Encoding.Default.GetBytes("userbob:qwerty"));
((HttpWebRequest)request).CookieContainer = new CookieContainer();
request.Headers["Authorization"] = "Basic " + authInfo;
((HttpWebRequest)request).UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
((HttpWebRequest)request).ContentType = "application/octet-stream";
var response = request.GetResponse();
最后一行有同样的例外。我觉得我缺少一些标题或设置来完全模仿浏览器行为。
有趣的是,如果我在任一解决方案中省略Authorization标头,我会得到401:未经授权的例外。这让我觉得我通过了授权而问题出在其他方面。我错过了什么?
答案 0 :(得分:0)
您必须通过转换为Base64来传递令牌:
var username = "xxxxxxx";
var password = "yyyyyyy";
var token = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + token);