Comment faire pour faire une requête Web HTTP POST

Comment puis-je faire une requête HTTP et envoyer des données en utilisant la méthode POST ? Je peux faire une demande GET mais je ne sais pas comment faire un POST .

Il existe plusieurs manières d’effectuer des requêtes HTTP GET et POST :


Méthode A: HttpClient

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

Actuellement l’approche privilégiée. Asynchrone. Version portable pour les autres plates-formes disponibles via NuGet .

 using System.Net.Http; 

Installer

Il est recommandé d’instancier un HttpClient pour la durée de vie de votre application et de le partager.

 private static readonly HttpClient client = new HttpClient(); 

POSTER

 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 responseSsortingng = await response.Content.ReadAsSsortingngAsync(); 

OBTENIR

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

Méthode B: Bibliothèques tierces

RestSharp

Bibliothèque testée et testée pour interagir avec les API REST. Portable. Disponible via NuGet .

Flurl.Http

Bibliothèque plus récente dotée d’une API et d’aides au test fluides. HttpClient sous le capot. Portable. Disponible via NuGet .

 using Flurl.Http; 

POSTER

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

OBTENIR

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

Méthode C: Héritage

Disponible dans: .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 

POSTER

 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 responseSsortingng = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

OBTENIR

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

Méthode D: WebClient (également maintenant héritée)

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

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

POSTER

 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 responseSsortingng = Encoding.Default.GetSsortingng(response); } 

OBTENIR

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

Demande GET simple

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

Demande 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); ssortingng responseInSsortingng = Encoding.UTF8.GetSsortingng(response); } 

MSDN a un exemple.

 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. ssortingng postData = "This is a test that posts this ssortingng 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. ssortingng responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); } } } 

Ceci est un exemple de travail complet d’envoi / réception de données au format JSON, j’ai utilisé 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 ssortingng Name { get; set; } public ssortingng Address { get; set; } public ssortingng Phone { get; set; } } public class Program { private static readonly HttpClient _Client = new HttpClient(); private static JavaScriptSerializer _Serializer = new JavaScriptSerializer(); static void Main(ssortingng[] args) { Run().Wait(); } static async Task Run() { ssortingng 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()); ssortingng responseText = await response.Content.ReadAsSsortingngAsync(); 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... /// Ssortingng data to POST on the server /// If you use some kind of Authorization you should use this ///  static async Task Request(HttpMethod pMethod, ssortingng pUrl, ssortingng 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 SsortingngContent(pJsonContent, Encoding.UTF8, "application/json"); httpRequestMessage.Content = httpContent; break; } return await _Client.SendAsync(httpRequestMessage); } } } 

Vous devez utiliser la classe WebRequest et la méthode GetRequestStream .

Voici un exemple.

Une solution simple (une seule ligne, sans vérification d’erreur, sans attente de réponse) que j’ai trouvée jusqu’à présent

 (new WebClient()).UploadSsortingngAsync(new Uri(Address), dataSsortingng);‏ 

utiliser avec précaution!

Lors de l’utilisation de l’espace de noms Windows.Web.Http , pour POST au lieu de FormUrlEncodedContent, nous écrivons HttpFormUrlEncodedContent. La réponse est également le type de HttpResponseMessage. Le rest est comme écrit par Evan Mulawski.

Vous pouvez utiliser IEnterprise.Easy-HTTP car il a intégré l’parsing de classe et la construction de requêtes:

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