C#: HttpClient with POST parameters

前端 未结 2 444
时光取名叫无心
时光取名叫无心 2020-12-09 08:06

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

string url = \"http://myserver/method?param1=1¶m2=2\"    
HttpClientHandler handler = new HttpCli         


        
相关标签:
2条回答
  • 2020-12-09 08:42

    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

    0 讨论(0)
  • 2020-12-09 08:48

    As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

    The querystring (get) parameters included in your url probably will not do anything.

    Try this:

    string url = "http://myserver/method";    
    string content = "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,content);
    

    HTH,

    bovako

    0 讨论(0)
提交回复
热议问题