我需要执行 cURL 请求以从 Web 获取 CSV 文件。我以前从未使用过 cURL,到目前为止,我通过谷歌看到的东西似乎没有意义:
cURL 调用需要如下所示:
curl --user username:password http://somewebsite.com/events.csv
我正在尝试使用的代码(我用它来获取基本的身份验证 XML 文件)
string URL = "http://somewebsite.com/events.csv";
string Username = "username";
string Password = "password";
WebClient req = new WebClient();
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(URL), "Basic", new NetworkCredential(Username, Password));
req.Credentials = myCache;
string results = null;
results = Encoding.UTF8.GetString(req.DownloadData(URL));
这只是返回登录屏幕的 html,因此不会进行身份验证。
请您参考如下方法:
我发现了问题。显然,当您在用户名字段中传递 @
符号(如电子邮件用户名)时,请求失败,因此必须将其转换为 base 64 字符串。以下是代码,以防其他人遇到此问题:
string url = "https://website.com/events.csv";
WebRequest myReq = WebRequest.Create(url);
string username = "username";
string password = "password";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
Console.ReadLine();