How to make an HTTP POST web request

后端 未结 14 2750
有刺的猬
有刺的猬 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:44

    Yet another way of doing it:

    using (HttpClient httpClient = new HttpClient())
    using (MultipartFormDataContent form = new MultipartFormDataContent())
    {
        form.Add(new StringContent(param1), "param1");
        form.Add(new StringContent(param2), "param2");
        using (HttpResponseMessage response = await httpClient.PostAsync(url, form))
        {
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
    }
    

    This way you can easily post a stream.

    0 讨论(0)
  • 2020-11-21 04:46

    When using Windows.Web.Http namespace, for POST instead of FormUrlEncodedContent we write HttpFormUrlEncodedContent. Also the response is type of HttpResponseMessage. The rest is as Evan Mulawski wrote down.

    0 讨论(0)
  • 2020-11-21 04:46

    You can also use Postman App for Windows, Linux or OSX. It is a complete web app & service test environment that involve all the request methods. You can find the latest version here.

    0 讨论(0)
  • 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<WebResponse> CallUri(string url, TimeSpan timeout)
    {
        var uri = new Uri(url);
        NameValueCollection rawParameters = HttpUtility.ParseQueryString(uri.Query);
        var parameters = new Dictionary<string, string>();
        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.
     }
    
    0 讨论(0)
  • There are some really good answers on here. Let me post a different way to set your headers with the WebClient(). I will also show you how to set an API key.

            var client = new WebClient();
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
            client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
            //If you have your data stored in an object serialize it into json to pass to the webclient with Newtonsoft's JsonConvert
            var encodedJson = JsonConvert.SerializeObject(newAccount);
    
            client.Headers.Add($"x-api-key:{ApiKey}");
            client.Headers.Add("Content-Type:application/json");
            try
            {
                var response = client.UploadString($"{apiurl}", encodedJson);
                //if you have a model to deserialize the json into Newtonsoft will help bind the data to the model, this is an extremely useful trick for GET calls when you have a lot of data, you can strongly type a model and dump it into an instance of that class.
                Response response1 = JsonConvert.DeserializeObject<Response>(response);
    
    0 讨论(0)
  • 2020-11-21 04:53

    This is a complete working example of sending/receiving data in JSON format, I used Visual Studio 2013 Express Edition:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.OleDb;
    using System.IO;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Script.Serialization;
    
    namespace ConsoleApplication1
    {
        class Customer
        {
            public string Name { get; set; }
            public string Address { get; set; }
            public string Phone { get; set; }
        }
    
        public class Program
        {
            private static readonly HttpClient _Client = new HttpClient();
            private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();
    
            static void Main(string[] args)
            {
                Run().Wait();
            }
    
            static async Task Run()
            {
                string url = "http://www.example.com/api/Customer";
                Customer cust = new Customer() { Name = "Example Customer", Address = "Some example address", Phone = "Some phone number" };
                var json = _Serializer.Serialize(cust);
                var response = await Request(HttpMethod.Post, url, json, new Dictionary<string, string>());
                string responseText = await response.Content.ReadAsStringAsync();
    
                List<YourCustomClassModel> serializedResult = _Serializer.Deserialize<List<YourCustomClassModel>>(responseText);
    
                Console.WriteLine(responseText);
                Console.ReadLine();
            }
    
            /// <summary>
            /// Makes an async HTTP Request
            /// </summary>
            /// <param name="pMethod">Those methods you know: GET, POST, HEAD, etc...</param>
            /// <param name="pUrl">Very predictable...</param>
            /// <param name="pJsonContent">String data to POST on the server</param>
            /// <param name="pHeaders">If you use some kind of Authorization you should use this</param>
            /// <returns></returns>
            static async Task<HttpResponseMessage> Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary<string, string> pHeaders)
            {
                var httpRequestMessage = new HttpRequestMessage();
                httpRequestMessage.Method = pMethod;
                httpRequestMessage.RequestUri = new Uri(pUrl);
                foreach (var head in pHeaders)
                {
                    httpRequestMessage.Headers.Add(head.Key, head.Value);
                }
                switch (pMethod.Method)
                {
                    case "POST":
                        HttpContent httpContent = new StringContent(pJsonContent, Encoding.UTF8, "application/json");
                        httpRequestMessage.Content = httpContent;
                        break;
    
                }
    
                return await _Client.SendAsync(httpRequestMessage);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题