Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • Email
  • Password

I've been doing this with RestSharp, but I'm trying to migrate off that.

How can I do this with HttpClient, please?

I have the following RestSharp code

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?

Take note: I'm doing a POST

Also, this is with the PCL assembly.

Lastly, can I add in a custom header. Say: "ILikeTurtles", "true".

like image 606
Pure.Krome Avatar asked Feb 16 '14 00:02

Pure.Krome


People also ask

Does RestSharp use HttpClient?

Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.

What is RestSharp C#?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.

Why use RestSharp?

RestSharp can take care of serializing the request body to JSON or XML and deserialize the response. It can also form a valid request URI based on different parameter kinds - path, query, form or body.


2 Answers

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 });
like image 88
Todd Menier Avatar answered Nov 01 '22 02:11

Todd Menier


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));
like image 26
daanl Avatar answered Nov 01 '22 04:11

daanl