简体   繁体   English

如何将此.NET RestSharp代码转换为Microsoft.Net.Http HttpClient代码?

[英]How can I convert this .NET RestSharp code to Microsoft.Net.Http HttpClient code?

I'm trying to figure out how to use HttpClient to POST some simple parameters. 我试图找出如何使用HttpClientPOST一些简单的参数。

  • Email 电子邮件
  • Password 密码

I've been doing this with RestSharp, but I'm trying to migrate off that. 我一直在用RestSharp做这个,但我正试图迁移它。

How can I do this with HttpClient , please? 我怎么能用HttpClient做到这一点,好吗?

I have the following RestSharp code 我有以下RestSharp代码

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

How can I convert that to use the (Microsoft.Net.Http) HttpClient class, instead? 我该如何转换它来使用(Microsoft.Net.Http) HttpClient类呢?

Take note: I'm doing a POST 请注意:我正在进行POST

Also, this is with the PCL assembly. 此外,这是PCL组件。

Lastly, can I add in a custom header. 最后,我可以添加自定义标头。 Say: "ILikeTurtles", "true" . 说: "ILikeTurtles", "true"

This should do it 这应该做到这一点

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));

If you're not opposed to using a library per se, as long as it's HttpClient under the hood, Flurl is another alternative. 如果您不反对使用库本身,只要它是引擎盖下的HttpClientFlurl就是另一种选择。 [disclaimer: I'm the author] [免责声明:我是作者]

This scenario would look like this: 这种情况看起来像这样:

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

This code isn't using HttpClient but it's using the System.Net.WebClient class, i guess it does the same thing though. 这段代码没有使用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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM