我正在尝试进行cURL调用以下载CSV文件,然后我将返回登录页面html。这是代码:
WebRequest myRequest = WebRequest.Create("https://website.com/medias/823533/events.csv");
myRequest.Credentials = new NetworkCredential("username", "password");
myRequest.Method = "GET";
myRequest.PreAuthenticate = true;
// Return the response.
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
Console.WriteLine(result);
Console.ReadLine();
C#中是否有简单的cURL方法?无论我尝试什么,这似乎都不起作用。
答案 0 :(得分:2)
我发现了这个问题。显然,当您在用户名字段中传递“@”符号(如电子邮件用户名)时,请求将失败,因此必须将其转换为基本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();