gpt4 book ai didi

c# - C# 中的 cURL 调用

转载 作者:行者123 更新时间:2023-11-30 21:08:10 26 4
gpt4 key购买 nike

我需要执行 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();

关于c# - C# 中的 cURL 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com