How to make an HTTP POST web request

后端 未结 14 2764
有刺的猬
有刺的猬 2020-11-21 04:31

Canonical
How can I make an HTTP request and send some data using the POST method?

14条回答
  •  离开以前
    2020-11-21 04:47

    This solution uses nothing but standard .NET calls.

    Tested:

    • In use in an enterprise WPF application. Uses async/await to avoid blocking the UI.
    • Compatible with .NET 4.5+.
    • Tested with no parameters (requires a "GET" behind the scenes).
    • Tested with parameters (requires a "POST" behind the scenes).
    • Tested with a standard web page such as Google.
    • Tested with an internal Java-based webservice.

    Reference:

    // Add a Reference to the assembly System.Web
    

    Code:

    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Web;
    
    private async Task CallUri(string url, TimeSpan timeout)
    {
        var uri = new Uri(url);
        NameValueCollection rawParameters = HttpUtility.ParseQueryString(uri.Query);
        var parameters = new Dictionary();
        foreach (string p in rawParameters.Keys)
        {
            parameters[p] = rawParameters[p];
        }
    
        var client = new HttpClient { Timeout = timeout };
        HttpResponseMessage response;
        if (parameters.Count == 0)
        {
            response = await client.GetAsync(url);
        }
        else
        {
            var content = new FormUrlEncodedContent(parameters);
            string urlMinusParameters = uri.OriginalString.Split('?')[0]; // Parameters always follow the '?' symbol.
            response = await client.PostAsync(urlMinusParameters, content);
        }
        var responseString = await response.Content.ReadAsStringAsync();
    
        return new WebResponse(response.StatusCode, responseString);
    }
    
    private class WebResponse
    {
        public WebResponse(HttpStatusCode httpStatusCode, string response)
        {
            this.HttpStatusCode = httpStatusCode;
            this.Response = response;
        }
        public HttpStatusCode HttpStatusCode { get; }
        public string Response { get; }
    }
    

    To call with no parameters (uses a "GET" behind the scenes):

     var timeout = TimeSpan.FromSeconds(300);
     WebResponse response = await this.CallUri("http://www.google.com/", timeout);
     if (response.HttpStatusCode == HttpStatusCode.OK)
     {
         Console.Write(response.Response); // Print HTML.
     }
    

    To call with parameters (uses a "POST" behind the scenes):

     var timeout = TimeSpan.FromSeconds(300);
     WebResponse response = await this.CallUri("http://example.com/path/to/page?name=ferret&color=purple", timeout);
     if (response.HttpStatusCode == HttpStatusCode.OK)
     {
         Console.Write(response.Response); // Print HTML.
     }
    

提交回复
热议问题