Kanonik
*Bagaimana saya dapat membuat permintaan HTTP dan mengirim beberapa data menggunakanPOST
metode?**
Yang bisa saya lakukan MENDAPATKAN
permintaan tapi tidak memiliki ide bagaimana untuk membuat POST
.
Ada beberapa cara untuk melakukan HTTP MENDAPATKAN
dan POST
permintaan:
Ini adalah pembungkus sekitar HttpWebRequest
. Bandingkan dengan WebClient
.
Tersedia di: .NET Framework 4.5+
, .NET Standar 1.1+
, .NET Core 1.0+
.
Saat ini, pendekatan yang lebih disukai. Asynchronous. Versi portabel untuk platform lain akan tersedia melalui NuGet.
using System.Net.Http;
Itu adalah recommended untuk instantiate satu HttpClient
untuk aplikasi anda's seumur hidup dan berbagi.
private static readonly HttpClient client = new HttpClient();
Lihat HttpClientFactory
untuk Ketergantungan larutan Injeksi.
POST
var nilai = baru Kamus<string, string> { { "thing1", "hello" }, { "thing2", "dunia" } };
var isi = new FormUrlEncodedContent(nilai-nilai);
var response = menunggu klien.PostAsync("http://www.example.com/recepticle.aspx", konten);
var responseString = menunggu respon.Konten.ReadAsStringAsync();
GET
var responseString = menunggu klien.GetStringAsync("http://www.example.com/recepticle.aspx");
Dicoba dan diuji perpustakaan untuk berinteraksi dengan REST Api. Portabel. Tersedia melalui NuGet.
Baru perpustakaan olahraga yang menguasai API dan pengujian pembantu. HttpClient di bawah tenda. Portabel. Tersedia melalui NuGet.
menggunakan Flurl.Http;
POST
var responseString = menunggu "http://www.example.com/recepticle.aspx" .PostUrlEncodedAsync(baru { thing1 = "hello", thing2 = "dunia" }) .ReceiveString();
GET
var responseString = menunggu "http://www.example.com/recepticle.aspx" .GetStringAsync();
Tersedia di: .NET Framework 1.1+
, .NET 2.0 Standar+
, .NET Core 1.0+
using System.Net;
using System.Text; // for class Encoding
using System.IO; // for StreamReader
POST
var request = (HttpWebRequest)WebRequest.Membuat("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello"); postData += "&thing2=" + Uri.EscapeDataString("dunia"); var data = Encoding.ASCII.GetBytes(postData);
permintaan.Metode = "POST"; permintaan.ContentType = "application/x-www-form-urlencoded"; permintaan.ContentLength = data.Panjang;
menggunakan (var stream = permintaan.GetRequestStream()) { stream.Write(data, 0, data.Panjang); }
var response = (HttpWebResponse)permintaan.GetResponse();
var responseString = new StreamReader(respon.GetResponseStream()).ReadToEnd();
GET
var request = (HttpWebRequest)WebRequest.Membuat("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)permintaan.GetResponse();
var responseString = new StreamReader(respon.GetResponseStream()).ReadToEnd();
Ini adalah pembungkus sekitar HttpWebRequest
. Bandingkan dengan HttpClient
.
Tersedia di: .NET Framework 1.1+
, BERSIH Standar 2.0+
, .NET Core 2.0+
using System.Net;
using System.Collections.Specialized;
POST
menggunakan (var client = new WebClient()) { var nilai = new NameValueCollection(); nilai-nilai["thing1"] = "hello"; nilai-nilai["thing2"] = "dunia";
var response = klien.UploadValues("http://www.example.com/recepticle.aspx", nilai);
var responseString = Encoding.Default.GetString(response); }
GET
menggunakan (var client = new WebClient()) { var responseString = klien.DownloadString("http://www.example.com/recepticle.aspx"); }
Sederhana MENDAPATKAN permintaan
using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
Sederhana permintaan 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);
}
MEDIA memiliki sampel.
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();
}
}
}
Ini adalah kerja lengkap contoh mengirim/menerima data dalam format JSON, saya digunakan 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);
}
}
}
Ada beberapa benar-benar jawaban yang baik di di sini. Biarkan saya posting cara yang berbeda untuk mengatur header dengan WebClient(). Saya juga akan menunjukkan kepada anda bagaimana untuk mengatur sebuah 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);
Solusi ini menggunakan apa-apa tapi standar .Panggilan NET.
Diuji:
Referensi:
// Add a Reference to the assembly System.Web
Kode:
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; }
}
Untuk memanggil dengan parameter tidak (menggunakan "MENDAPATKAN" di belakang layar):
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.
}
Untuk memanggil dengan parameter (menggunakan "POST" di belakang layar):
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.
}
Anda dapat menggunakan IEnterprise.Mudah-HTTP sejak itu telah dibangun di kelas parsing dan query bangunan:
await new RequestBuilder<ExampleObject>()
.SetHost("https://httpbin.org")
.SetContentType(ContentType.Application_Json)
.SetType(RequestType.Post)
.SetModelToSerialize(dto)
.Build()
.Execute();
I'm penulis dari perpustakaan sehingga merasa bebas untuk mengajukan pertanyaan atau periksa kode di github
Jika anda suka menguasai API anda dapat menggunakan Kecil.RestClient. It's tersedia di Nuget
var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
// POST
var city = new City() { Name = "Paris", Country = "France" };
// With content
var response = await client.PostRequest("City", city)
.ExecuteAsync<bool>();
Harapan yang membantu!
Mengapa hal ini tidak benar-benar sepele ? melakukan permintaan tidak dan terutama tidak berurusan dengan hasil-hasil dan sepertinya ada beberapa .NET bug yang terlibat serta - lihat https://social.msdn.microsoft.com/Forums/en-US/d8d87789-0ac9-4294-84a0-91c9fa27e353/bug-in-httpclientgetasync-should-throw-webexception-not-taskcanceledexception?forum=netfxnetcom
Saya berakhir dengan kode ini:
`` statis async Task<(bool Sukses, WebExceptionStatus WebExceptionStatus, HttpStatusCode? HttpStatusCode, string ResponseAsString)> HttpRequestAsync(HttpClient httpClient, string url, string postBuffer = null, CancellationTokenSource cts = null) { try { HttpResponseMessage resp = null;
jika (postBuffer null) { resp = cts adalah null ? menanti httpClient.GetAsync(url) : menanti httpClient.GetAsync(url, cts.Token);
} else { menggunakan (var httpContent = new StringContent(postBuffer)) { resp = cts adalah null ? menanti httpClient.PostAsync(url, httpContent) : menanti httpClient.PostAsync(url, httpContent, cts.Token); } }
var respString = menunggu resp.Konten.ReadAsStringAsync(); kembali (resp.IsSuccessStatusCode, WebExceptionStatus.Sukses, resp.StatusCode, respString);
} catch (WebException ex) { WebExceptionStatus status = ex.Status; if (status == WebExceptionStatus.ProtocolError) { // Mendapatkan HttpWebResponse sehingga anda dapat memeriksa kode status HTTP. menggunakan (HttpWebResponse httpResponse = (HttpWebResponse)ex.Response) { return (false, status, httpResponse.StatusCode, httpResponse.StatusDescription); } } else { return (false, status, null, ex.ToString()); }
} catch (TaskCanceledException ex) { jika (ex.CancellationToken == cts.Token) { // nyata pembatalan, dipicu oleh pemanggil return (false, WebExceptionStatus.RequestCanceled, null, ex.ToString()); } else { // web request timeout (mungkin hal-hal lain!?) return (false, WebExceptionStatus.Timeout, null, ex.ToString()); }
} catch (Exception ex) { return (false, WebExceptionStatus.UnknownError, null, ex.ToString()); } } ``
Ini akan melakukan GET atau POST tergantung jika postBuffer
adalah null atau tidak
jika Kesuksesan adalah benar respon yang kemudian akan di ResponseAsString
jika Sukses adalah palsu anda dapat memeriksa WebExceptionStatus
, HttpStatusCode
dan ResponseAsString
untuk mencoba untuk melihat apa yang salah.
Saya menyambut komentar tentang hal ini karena saya masih tidak yakin ini mencakup semua kasus.