I'm trying to figure out how to use HttpClient
to POST
some simple parameters.
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"
.
Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.
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.
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.
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 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With