Cómo hacer una solicitud web HTTP POST

¿Cómo puedo hacer una solicitud HTTP y enviar algunos datos usando el método POST ? Puedo hacer la solicitud GET pero no tengo idea de cómo hacer un POST .

Hay varias formas de realizar solicitudes HTTP GET y POST :


Método A: HttpClient

Disponible en: .NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+

Actualmente el enfoque preferido. Asincrónico. Versión portátil para otras plataformas disponible a través de NuGet .

 using System.Net.Http; 

Preparar

Se recomienda crear una instancia de HttpClient para la vida útil de su aplicación y compartirla.

 private static readonly HttpClient client = new HttpClient(); 

ENVIAR

 var values = new Dictionary { { "thing1", "hello" }, { "thing2", "world" } }; var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content); var responseString = await response.Content.ReadAsStringAsync(); 

OBTENER

 var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx"); 

Método B: Bibliotecas de terceros

RestSharp

Biblioteca probada para interactuar con API REST. Portátil. Disponible a través de NuGet .

Flurl.Http

Biblioteca más nueva con una API fluida y ayudantes de prueba. HttpClient bajo el capó. Portátil. Disponible a través de NuGet .

 using Flurl.Http; 

ENVIAR

 var responseString = await "http://www.example.com/recepticle.aspx" .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" }) .ReceiveString(); 

OBTENER

 var responseString = await "http://www.example.com/recepticle.aspx" .GetStringAsync(); 

Método C: Legado

Disponible en: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+

 using System.Net; using System.Text; // for class Encoding using System.IO; // for StreamReader 

ENVIAR

 var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); var postData = "thing1=hello"; postData += "&thing2=world"; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

OBTENER

 var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

Método D: WebClient (también ahora heredado)

Disponible en: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 2.0+

 using System.Net; using System.Collections.Specialized; 

ENVIAR

 using (var client = new WebClient()) { var values = new NameValueCollection(); values["thing1"] = "hello"; values["thing2"] = "world"; var response = client.UploadValues("http://www.example.com/recepticle.aspx", values); var responseString = Encoding.Default.GetString(response); } 

OBTENER

 using (var client = new WebClient()) { var responseString = client.DownloadString("http://www.example.com/recepticle.aspx"); } 

Solicitud GET simple

 using System.Net; ... using (var wb = new WebClient()) { var response = wb.DownloadString(url); } 

Solicitud POST simple

 using System.Net; using System.Collections.Specialized; ... using (var wb = new WebClient()) { var data = new NameValueCollection(); data["username"] = "myUser"; data["password"] = "myPassword"; var response = wb.UploadValues(url, "POST", data); string responseInString = Encoding.UTF8.GetString(response); } 

MSDN tiene una muestra.

 using System; using System.IO; using System.Net; using System.Text; namespace Examples.System.Net { public class WebRequestPostExample { public static void Main() { // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx"); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. string postData = "This is a test that posts this string to a Web server."; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. WebResponse response = request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); } } } 

Este es un ejemplo completo de trabajo de envío / recepción de datos en formato JSON, utilicé VS2013 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 responseText = await response.Content.ReadAsStringAsync(); List serializedResult = _Serializer.Deserialize>(responseText); Console.WriteLine(responseText); Console.ReadLine(); } ///  /// Makes an async HTTP Request ///  /// Those methods you know: GET, POST, HEAD, etc... /// Very predictable... /// String data to POST on the server /// If you use some kind of Authorization you should use this ///  static async Task Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary 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); } } } 

Necesita usar la clase WebRequest y el método GetRequestStream .

Aquí hay un ejemplo.

Solución simple (de una sola línea, sin verificación de errores, sin esperar respuesta) que he encontrado hasta ahora

 (new WebClient()).UploadStringAsync(new Uri(Address), dataString);‏ 

usar con precaución!

Al usar el espacio de nombres Windows.Web.Http , para POST en lugar de FormUrlEncodedContent, escribimos HttpFormUrlEncodedContent. También la respuesta es tipo de HttpResponseMessage. El rest es como Evan Mulawski anotó.

Puede usar IEnterprise.Easy-HTTP ya que ha incorporado análisis de clase y creación de consultas:

 await new RequestBuilder() .SetHost("https://httpbin.org") .SetContentType(ContentType.Application_Json) .SetType(RequestType.Post) .SetModelToSerialize(dto) .Build() .Execute();