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

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 07:16:33

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. [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.

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);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!