【问题标题】:Issue with reproducing the results of a cURL command in code在代码中重现 cURL 命令结果的问题
【发布时间】:2014-04-25 23:43:21
【问题描述】:

我正在尝试使用 .NET 执行以下操作

如果我的用户名是 test 并且密码是 password,那么使用 HttpClient 的 C# 代码会是什么样子?

HTTP Method: GET
URL: http://webapi.ebayclassifieds.com/webapi/categories
Sample command:
curl --digest -u{username}:{password} http://webapi.ebayclassifieds.com/webapi/categories

这是我所拥有的,但我没有得到 html:

 var client = new HttpClient();

 var requestContent = new FormUrlEncodedContent(new[] { 
    new KeyValuePair<string, string>("-u", "{test}:{password}") });

 HttpResponseMessage response = await client.PostAsync(
    "http://webapi.ebayclassifieds.com/webapi/categories", requestContent);

 // Get the response content.
 HttpContent responseContent = response.Content;

 var blah = response.Content.ReadAsStringAsync();

【问题讨论】:

  • 您已经用 C# 尝试过什么?请试一试,如果遇到问题,请告诉我们。
  • Zoinky,gimme-teh-codez 帖子在 SO 上并不受欢迎。在发布这样的问题之前,请先尝试一下。请删除此问题并在您有代码要分享时回来。
  • @PaulSasik 不要鼓励人们删除然后重新发布相同的问题。他们应该编辑问题以解决它,而不是一遍又一遍地重新发布。
  • 我一般同意你的看法@Servy,但 IMO 这是一个特例。我建议删除该帖子,因为该帖子获得了 7 票反对并且很快被关闭/搁置。在受到如此负面的反应之后,即使是出色的编辑工作也不太可能获得关注。
  • @PaulSasik 不断删除并重新提出相同的问题是问题禁令的捷径。

标签: c# curl .net-4.5


【解决方案1】:

试试这个:

CredentialCache credCache = new CredentialCache();
credCache.Add (new Uri ("http://webapi.ebayclassifieds.com"), "Digest",  new NetworkCredential ("username", "passwd"));

之后使用凭证缓存构造HttpClient

var httpClient = new HttpClient( new HttpClientHandler { Credentials = credCache});

其余的过程是相同的。如果您执行 http POST,则使用 PostAsync,对于 http GET,使用 GetAsync

您可以从here 找到有关CredentialCache 的更多详细信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多