来自控制台应用程序C#的cURL调用
本文关键字:cURL 调用 应用程序 控制台 | 更新日期: 2023-09-27 18:28:37
我正在尝试进行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方法吗?不管我怎么做,这似乎都不起作用。
我发现了这个问题。显然,当您在username字段中传递"@"符号(如电子邮件用户名中的符号)时,请求会失败,因此必须将其转换为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();