Canonical
Como posso fazer um pedido HTTP e enviar alguns dados utilizando oPOST
method?
Eu posso fazer um pedido "GET" mas não tenho idéia de como fazer um "POST".
Existem várias formas de realizar pedidos HTTP GET
e POST
:
Este é um invólucro em torno de HttpWebRequest
. Compare com o WebClient
.
Disponível em: .NET Framework 4.5+
, .NET Standard 1.1+
, .NET Core 1.0+
.
Actualmente, a abordagem preferida. Assíncrona. Versão portátil para outras plataformas disponível via NuGet.
using System.Net.Http;
É recomendado instanciar um HttpClient
para a vida útil da sua aplicação e compartilhá-la.
private static readonly HttpClient client = new HttpClient();
Veja HttpClientFactory
para uma solução de Injeção de Dependência.
PÓS".
var valores = novo Dicionário<string, string>
{
"coisa1", "olá",
{"coisa2", "mundo" }
};
var content = novo FormUrlEncodedContent(valores);
var resposta = aguardar client.PostAsync("http://www.example.com/recepticle.aspx", conteúdo);
var responseString = aguarda resposta.Content.ReadAsStringAsync();
"ORÇAMENTO''.
var responseString = aguarda client.GetStringAsync("http://www.example.com/recepticle.aspx");
*RestSharp***
Biblioteca experimentada e testada para interagir com as APIs REST. Portáteis. Disponível através de NuGet.
*Flurl.Http***
Biblioteca mais recente com um API fluente e ajudantes de teste. Cliente HttpClient debaixo do capô. Portátil. Disponível através de NuGet.
usando Flurl.Http;
PÓS".
var responseString = aguarde "http://www.example.com/recepticle.aspx
.PostUrlEncodedAsync(novo { thing1 = "olá", thing2 = "mundo" })
RecebaString();
"ORÇAMENTO''.
var responseString = aguarde "http://www.example.com/recepticle.aspx
GetStringAsync();
Disponível em: .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
PÓS".
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("olá");
postData += "&thing2=" + Uri.EscapeDataString("mundo");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = "data.Length";
usando (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var resposta = (HttpWebResponse)request.GetResponse();
var responseString = novo StreamReader(response.getResponseStream()).ReadToEnd();
"ORÇAMENTO''.
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var resposta = (HttpWebResponse)request.GetResponse();
var responseString = novo StreamReader(response.getResponseStream()).ReadToEnd();
Este é um invólucro em torno de HttpWebRequest
. Compare com HttpClient
.
Disponível em: "Framework 1.1+.NET", "NET Standard 2.0+", "Core 2.0+.NET".
using System.Net;
using System.Collections.Specialized;
PÓS".
usando (var client = novo Cliente Web())
{
var valores = novo NomeValueCollection();
valores["thing1"] = "olá";
valores["thing2"] = "mundo";
var resposta = client.UploadValues("http://www.example.com/recepticle.aspx", valores);
var responseString = Encoding.Default.GetString(response);
}
"ORÇAMENTO''.
usando (var client = novo Cliente Web())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
Pedido simples de GET
using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
Pedido simples de 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 tem uma amostra.
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();
}
}
}