C#: HttpClient with POST parameters

133,237

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Share:
133,237
Vahid
Author by

Vahid

A detail-oriented and fast learner, Front-End developer with more than 8 years of experience leveraging JavaScript to build responsive and complex web applications on budget and on time, driving business growth with the focus on UX and performance. Help teams to grow their knowledge and learn from them to grow.

Updated on March 27, 2020

Comments

  • Vahid
    Vahid about 4 years

    I use codes below to send POST request to a server:

    string url = "http://myserver/method?param1=1&param2=2"    
    HttpClientHandler handler = new HttpClientHandler();
    HttpClient httpClient = new HttpClient(handler);
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
    HttpResponseMessage response = await httpClient.SendAsync(request);
    

    I don't have access to the server to debug but I want to know, is this request sent as POST or GET?

    If it is GET, How can I change my code to send param1 & param2 as POST data (not in the URL)?

  • Mark Szabo
    Mark Szabo almost 7 years
    @JohnCroneh this isn't working anymore. Please accept the other answer below!
  • R. McManaman
    R. McManaman almost 7 years
    @JohnCroneh please change the accepted answer to one that works
  • HellBaby
    HellBaby over 6 years
    @R.McManaman Actually it's a good answer if you would go with creating an no known method type. It's missing some "using" to make sure that it disposes and a "make sure it's converted", but it follows the PostAsync wrapper implementation.
  • d00d
    d00d about 4 years
    That version does not work for me. The parameter received by the controller action is always null.
  • aloisdg
    aloisdg about 4 years
    @d00d feel free to post a new question linked to this one explaining your problem.
  • Hosein Aqajani
    Hosein Aqajani over 3 years
    and what about sending Get request by parameters?
  • aloisdg
    aloisdg over 3 years
    @HoseinAqajani I think it would be a great question to ask in a new post. Feel free to link it here as comment.
  • Beltway
    Beltway over 2 years
    List<KeyValuePair<string, string>> is more concise as query parameter keys aren't necessarily unique.
  • aloisdg
    aloisdg over 2 years
    While you are true (so here is an upvote), I dont like query parameter with duplicate. I dont only code in .net and since there is no spec about this, different server handle duplicate differently. Beside, duplicate can lead to HPP.