HTTP POST 웹 요청을 만드는 방법
Canonical
HTTP 요청을 만들고 메서드를 사용하여 일부 데이터를 보내려면 어떻게POST
해야합니까?
GET
요청을 할 수는 있지만 POST
.
HTTP GET
및 POST
요청 을 수행하는 방법에는 여러 가지가 있습니다 .
방법 A : HttpClient (선호)
이것은 주위의 래퍼 HttpWebRequest
입니다. 와 비교하십시오WebClient
.
가능 : .NET Framework 4.5+
, .NET Standard 1.1+
, .NET Core 1.0+
.
현재 선호되는 접근 방식입니다. 비동기. NuGet을 통해 사용할 수있는 다른 플랫폼 용 휴대용 버전입니다 .
using System.Net.Http;
설정
그것은되는 추천 인스턴스화 하나에 HttpClient
응용 프로그램의 수명과 공유 그것을 위해.
private static readonly HttpClient client = new HttpClient();
HttpClientFactory
종속성 주입 솔루션을 참조하십시오 .
POST
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();
GET
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
방법 B : 타사 라이브러리
-
REST API와 상호 작용하기 위해 검증 된 라이브러리입니다. 가지고 다닐 수 있는. NuGet을 통해 사용할 수 있습니다.
-
유창한 API와 테스트 도우미를 자랑하는 최신 라이브러리. 내부의 HttpClient. 가지고 다닐 수 있는. NuGet을 통해 사용할 수 있습니다.
using Flurl.Http;
POST
var responseString = await "http://www.example.com/recepticle.aspx" .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" }) .ReceiveString();
GET
var responseString = await "http://www.example.com/recepticle.aspx" .GetStringAsync();
방법 C : HttpWebRequest (신규 작업에는 권장되지 않음)
가능 : .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
POST
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); var postData = "thing1=" + Uri.EscapeDataString("hello"); postData += "&thing2=" + Uri.EscapeDataString("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();
GET
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
방법 D : WebClient (신규 작업에는 권장되지 않음)
이것은 주위의 래퍼 HttpWebRequest
입니다. 와 비교하십시오HttpClient
.
가능 : .NET Framework 1.1+
, NET Standard 2.0+
,.NET Core 2.0+
using System.Net;
using System.Collections.Specialized;
POST
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); }
GET
using (var client = new WebClient()) { var responseString = client.DownloadString("http://www.example.com/recepticle.aspx"); }
간단한 GET 요청
using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
간단한 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 에는 샘플이 있습니다.
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();
}
}
}
이것은 JSON 형식으로 데이터를 송수신하는 완전한 작업 예이며 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);
}
}
}
There are some really good answers on here. Let me post a different way to set your headers with the WebClient(). I will also show you how to set an 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);
Simple (one-liner, no error checking, no wait for response) solution i've found so far
(new WebClient()).UploadStringAsync(new Uri(Address), dataString);
use with caution!
This solution uses nothing but standard .NET calls.
Tested:
- In use in an enterprise WPF application. Uses async/await to avoid blocking the UI.
- Compatible with .NET 4.5+.
- Tested with no parameters (requires a "GET" behind the scenes).
- Tested with parameters (requires a "POST" behind the scenes).
- Tested with a standard web page such as Google.
- Tested with an internal Java-based webservice.
Reference:
// Add a Reference to the assembly System.Web
Code:
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; }
}
To call with no parameters (uses a "GET" behind the scenes):
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.
}
To call with parameters (uses a "POST" behind the scenes):
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.
}
When using Windows.Web.Http namespace, for POST instead of FormUrlEncodedContent we write HttpFormUrlEncodedContent. Also the response is type of HttpResponseMessage. The rest is as Evan Mulawski wrote down.
You can use IEnterprise.Easy-HTTP since it has built in class parsing and query building:
await new RequestBuilder<ExampleObject>()
.SetHost("https://httpbin.org")
.SetContentType(ContentType.Application_Json)
.SetType(RequestType.Post)
.SetModelToSerialize(dto)
.Build()
.Execute();
I'm the author of the library so feel free to ask questions or check the code in github
If you like fluent API you can use Tiny.RestClient. It's available at 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>();
Hope that helps!
참고URL : https://stackoverflow.com/questions/4015324/how-to-make-http-post-web-request
'Nice programing' 카테고리의 다른 글
새 탭 또는 창에서 링크 열기 (0) | 2020.09.27 |
---|---|
PHP에서 stdClass는 무엇입니까? (0) | 2020.09.27 |
Google의 호스팅 된 jQuery를 사용하는 가장 좋은 방법이지만 Google의 호스팅 된 라이브러리로 대체 실패 (0) | 2020.09.27 |
30 분 후에 PHP 세션을 만료하려면 어떻게합니까? (0) | 2020.09.27 |
객체에 JavaScript의 키가 있는지 어떻게 확인합니까? (0) | 2020.09.27 |