【问题标题】:How can I convert this .NET RestSharp code to Microsoft.Net.Http HttpClient code?如何将此 .NET RestSharp 代码转换为 Microsoft.Net.Http HttpClient 代码?
【发布时间】:2014-02-16 00:13:40
【问题描述】:

我正在尝试弄清楚如何使用HttpClientPOST 一些简单的参数。

  • 电子邮件
  • 密码

我一直在使用 RestSharp 执行此操作,但我正在尝试迁移。

请问HttpClient 怎么做?

我有以下 RestSharp 代码

var restRequest = new RestRequest("account/authenticate", Method.POST);
restRequest.AddParameter("Email", email);
restRequest.AddParameter("Password", password);

如何将其转换为使用 (Microsoft.Net.Http) HttpClient 类?

注意:我正在做一个 POST

另外,这与 PCL 程序集有关。

最后,我可以添加自定义标题吗?说:"ILikeTurtles", "true"

【问题讨论】:

  • 您的两个问题之前都已得到解答,请参阅.NET HttpClient. How to POST string value?Adding Http Headers to HttpClient (ASP.NET Web API)。尝试使用搜索。
  • ...在这里稍等。现在真的有 三个 HttpClient 课程吗? System.Net.Http.HttpClientMicrosoft.Net.Http.HttpClientWindows.Web.Http.HttpClient?真的吗,微软?真的吗?
  • 这是一个非常好的问题。我只读过Microsoft.Net.HttpClient .. 真的有-三个- ??
  • @Charles 有两个。 System.Net.Http.HttpClient 位于 nuget 包 Microsoft.Net.Http 和 Windows.Web.HttpClient 中,它是本机实现。
  • @Pure.Krome 我可能知道您为什么决定使用 Microsoft.Net.HttpClient 而不是 RestSharp ..后者的语法似乎更具可读性

标签: c# .net restsharp dotnet-httpclient


【解决方案1】:

应该这样做

var httpClient = new HttpClient();

httpClient.DefaultRequestHeaders.Add("ILikeTurtles", "true");

var parameters = new Dictionary<string, string>();
parameters["Email"] = "myemail";
parameters["Password"] = "password";

var result = await httpClient.PostAsync("http://www.example.com/", new FormUrlEncodedContent(parameters));

【讨论】:

    【解决方案2】:

    如果您不反对使用库本身,只要它是 HttpClient 在引擎盖下,Flurl 是另一种选择。 [免责声明:我是作者]

    这个场景看起来像这样:

    var result = await "http://www.example.com"
        .AppendPathSegment("account/authenticate")
        .WithHeader("ILikeTurtles", "true")
        .PostUrlEncodedAsync(new { Email = email, Password = password });
    

    【讨论】:

      【解决方案3】:

      这段代码没有使用 HttpClient,但它使用了 System.Net.WebClient 类,我猜它做同样的事情。

      private static void Main(string[] args)
          {
              string uri = "http://www.example.com/";
              string email = "email@example.com";
              string password = "secret123";
      
              var client = new WebClient();
      
              // Adding custom headers
              client.Headers.Add("ILikeTurtles", "true");
      
              // Adding values to the querystring
              var query = HttpUtility.ParseQueryString(string.Empty);
              query["email"] = email;
              query["password"] = password;
              string queryString = query.ToString();
      
              // Uploadstring does a POST request to the specified server
              client.UploadString(uri, queryString);
          }
      

      【讨论】:

        猜你喜欢
        • 2017-11-23
        • 2022-07-08
        • 1970-01-01
        • 1970-01-01
        • 2019-11-19
        • 2019-05-26
        • 2018-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多