Comment faire HTTP POST demande web
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 n'ai aucune idée de comment faire un POST
.
8 réponses
Il existe plusieurs façons D'exécuter les requêtes HTTP GET
et POST
:
Méthode Un: HttpClient
Disponible dans:. NET Framework 4.5+,. net Standard 1.1+,. net Core 1.0 +
Actuellement l'approche préférée. Asynchrone. Version Portable pour d'autres plates-formes disponibles via NuGet .
using System.Net.Http;
le programme d'Installation
Il est recommandé d'instancier un HttpClient
pour la durée de vie et le partage de votre application il.
private static readonly HttpClient client = new HttpClient();
poste
var values = new Dictionary<string, string>
{
{ "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();
obtenir
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
Méthode B: bibliothèques tierces
Bibliothèque éprouvée pour interagir avec les API REST. Portable. Disponible via NuGet .
Bibliothèque plus récente arborant une API fluide et des aides de test. HttpClient sous le capot. Portable. Disponible via NuGet .
using Flurl.Http;
poste
var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();
obtenir
var responseString = await "http://www.example.com/recepticle.aspx"
.GetStringAsync();
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
poste
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();
obtenir
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Méthode D: WebClient (également maintenant hérité)
Disponible dans:. NET Framework 1.1+,. Net Standard 2.0+,. net Core 2.0+
using System.Net;
using System.Collections.Specialized;
poste
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);
}
obtenir
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
Simple demande GET
using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
Simple demande POST
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 dispose d'un échantillon.
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();
}
}
}
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 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);
}
}
}
Solution Simple (one-liner, pas de vérification d'erreur, pas d'attente de réponse) que j'ai trouvée jusqu'à présent
(new WebClient()).UploadStringAsync(new Uri(Address), dataString);
Utiliser avec prudence!
Lorsque vous utilisez Windows.Web.Http namespace, pour POST au lieu de FormUrlEncodedContent nous écrivons HttpFormUrlEncodedContent. La réponse est également de type HttpResponseMessage. Le reste est comme Evan Mulawski a écrit.
Vous pouvez utiliser IEnterprise.Easy-HTTP puisqu'il a intégré l'analyse de classe et la construction de requêtes:
await new RequestBuilder<ExampleObject>()
.SetHost("https://httpbin.org")
.SetContentType(ContentType.Application_Json)
.SetType(RequestType.Post)
.SetModelToSerialize(dto)
.Build()
.Execute();
Je suis l'auteur de la bibliothèque, alors n'hésitez pas à poser des questions ou de vérifier le code de github