표준
* 'POST' 방법을 사용하여 HTTP 요청을 생성하고 일부 데이터를 전송하려면 어떻게 해야 합니까?**
GET 요청은 할 수 있지만 POST는 어떻게 해야 할지 모르겠다.
HTTP 'GET' 및 'POST' 요청을 수행하는 방법은 다음과 같습니다.
이것은 'HttpWebRequest'에 대한 포장지입니다. 'WebClient'와 비교해 보십시오.
사용 가능: '.NET Framework 4.5 이상.NET 표준 1.1+'.NET Core 1.0+'.
현재 선호하는 접근 방식입니다. 비동기적. [NuGet](https://www.nuget.org/packages/Microsoft을 통해 다른 플랫폼용 휴대용 버전 제공.Net.Http).
using System.Net.Http;
애플리케이션 수명 동안 하나의 'HttpClient'를 인스턴스화하여 공유하는 것이 좋습니다.
private static readonly HttpClient client = new HttpClient();
종속성 주입 솔루션은 'HttpClientFactory'를 참조하십시오.
'포스트'
var 값 = 새 사전<string, string>
{
{ "thing1", "안녕하세요";,
{ "사물", "세계"}
};
var content = 새 FormUrlEncodedContent(값);
var response = 클라이언트를 기다립니다.PostAsync("http://www.example.com/recepticle.aspx", 콘텐츠);
varresponseString = 응답을 기다립니다.내용.ReadAsStringAsync();
'GET'
varresponseString = wait client입니다.GetStringAsync("http://www.example.com/recepticle.aspx");
REST API와 상호 작용하기 위해 라이브러리를 시도하고 테스트했습니다. 휴대용. NuGet을 통해 이용할 수 있습니다.
최신 라이브러리에는 유창한 API와 테스트 도우미가 있습니다. 후드 아래에 HttpClient가 있습니다. 휴대용. [NuGet](https://www.nuget.org/packages/Flurl을 통해 이용할 수 있습니다.Http).
Flurl 사용.Http;
'포스트'
varresponseString = wait & http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(새 {thing1 = "안녕하세요", thing2 = "world" })
.ReceiveStreceiveString
'GET'
varresponseString = wait & http://www.example.com/recepticle.aspx"
.GetStringAsync();
사용 가능: '.NET Framework 1.1+.NET 표준 2.0 이상.NET Core 1.0+'
using System.Net;
using System.Text; // for class Encoding
using System.IO; // for StreamReader
'포스트'
var 요청 =(HttpWebRequest)웹 요청.만들기("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += &&thing2=& + Uri.EscapeDataString("world");
var data = 인코딩입니다.ASCII.GetBytes(포스트 데이터);
부탁한다.방법 = "POST";
부탁한다.ContentType = "application/x-www-form-urlencoded";
부탁한다.ContentLength = 데이터.길이
사용(var stream = 요청).GetRequestStream()
{
개울.쓰기(데이터, 0, 데이터).길이);
}
var response =(HttpWebResponse) 요청입니다.응답 가져오기();
varresponseString = 새 스트림 판독기(응답)입니다.응답 스트림()을 가져옵니다.읽기 종료();
'GET'
var 요청 =(HttpWebRequest)웹 요청.만들기("http://www.example.com/recepticle.aspx");
var response =(HttpWebResponse) 요청입니다.응답 가져오기();
varresponseString = 새 스트림 판독기(응답)입니다.응답 스트림()을 가져옵니다.읽기 종료();
이것은 'HttpWebRequest'에 대한 포장지입니다. 'HttpClient'와 비교해 보십시오.
사용 가능: '.NET Framework 1.1+, 'NET Standard 2.0+'.NET 코어 2.0+'
using System.Net;
using System.Collections.Specialized;
'포스트'
(varclient = new WebClient() 사용)
{
var values = new NameValueCollection();
values ["thing1" = "안녕";
가치["thing2"] = "세계";
var response = 클라이언트입니다.값 업로드("http://www.example.com/recepticle.aspx", 값);
varresponseString = 인코딩입니다.체납.GetString(응답);
}
'GET'
(varclient = new WebClient() 사용)
{
varresponseString = 클라이언트입니다.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();
}
}
}
이는 완전한 apc® 예는 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);
}
}
}
정말 좋은 답변 여기 있는 경우도 있다. Let me 게시물로의 각기 다른 방식으로 헤더도 웹클리나 () 를 설정합니다. 또한 주요 내아기마저도 API 를 설정하는 방법을 알려드리겠습니다.
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);
이 솔루션은 것 외에는 아무것도 표준 .NET 있다.
테스트됨:
참조:
// Add a Reference to the assembly System.Web
코드:
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; }
}
매개 변수 없이 호출 (는 " 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.
}
함께 불러 매개 변수 () 는 " 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.
}
IEnterprise.Easy-HTTP 사용할 수 있는 바 있기 때문에 동급 구축됨 쿼리하지 구문 분석 및 건물:
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
await new RequestBuilder<ExampleObject>()
.SetHost("https://httpbin.org")
.SetContentType(ContentType.Application_Json)
.SetType(RequestType.Post)
.SetModelToSerialize(dto)
.Build()
.Execute();
끝 - < 스니핏 >;!
티니콜레스트클리나 fluent apiu 같은 경우 사용할 수 있습니다. # 39 의 it& http://ipw2100.sourceforge. 누제
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>();
도움이 되길 바란다!
그 이유는 전혀 없는 사소한? 특히 요청인지 하고 있지 않으며 .NET 관련된 몇 가지 버그를 다루는 결과와 같다 - 지켜보리니 포럼 = 네프스네컴 아니라 https://social.msdn.microsoft.com/Forums/en-US/d8d87789-0ac9-4294-84a0-91c9fa27e353/bug-in-httpclientgetasync-should-throw-webexception-not-taskcanceledexception?
내가 됐지 대체하십시오 코드:
"' 정적 비동기 Task<, (부울 성공, 베베스스티언스테우스 베베스스티언스테우스, 하토프스테우스코드? 하토프스테우스코드, 문자열 레스폰지아스트링) >. 하트프리퀘스타지 놀스 (하테프클리나 하테프클리나, 문자열 uirl, 문자열 포스트부퍼 = null, 칸첼이션tok엔수르스 cts = null) { try { 하테프레스폰세메사게 응답 = null;
if (포스트부퍼 널임) { 응답 = cts 널임? 기다리는 하테프클리앵 t.게타지 놀스 (url): 기다리는 하테프클리앵 t.게타지 놀스 (url, cts. 토큰인지);
} else { 사용 (var 하테프콘텐토 = new 스테링콘텐토 (포스트부퍼) { 응답 = cts 널임? 기다리는 하테프클리앵 t.포스타지 놀스 (url, 하테프콘텐토): 기다리는 하테프클리앵 t.포스타지 놀스 (url, 하테프콘텐토, cts. 토큰인지); } }
var 레프스트링 = 기다리는 관련어 콘텐t.레달스트린가지 놀스 (); 반환 (, 관련어, 레스피아수세스스테우스코드 베베스스티언스테우스.수세스 스테우스코드 레프스트링);
(베베스세페시옹 ex) {} catch 상태, 베베스스티언스테우스 상태 = emailxtender. if (상태 = 베베스스티언스테우스 스프로토콜로르) { Http 상태 코드 // 프레젠테이션이든 하테프웨브레스폰지 도왔으매 확인할 수 있습니다. 사용 (하테프웨브레스폰지 하테프레스폰지 = (하테프웨브레스폰지) 에스트레스폰지) { 반환 (false, 상태, 하테프레스폰지리스테우스코드, 하테프레스폰지리스테우스데스크리프션); } } else { 반환 (false, 상태, nulll, 확장 ToString ()); }
(타스카칸첼더스세페시옹 ex) {} catch if (= 렉스칸첼라티온트킨 cts. 토큰인지) { 실제 취소, 의해 트리거됩니다 요청자에게 // 반환 (false, 베베스스티언스테우스트리퀘스트칸슬레드, null emailxtender. ToString ()); } else { // 웹 reques 시간초과했습니다 (또는 다른 것들을!?) 반환 (false, 베베스스티언스테우스 스타임우스, null emailxtender. ToString ()); }
(예외 ex) {} catch 반환 (false, 베베스스티언스테우스.언크노너로, null emailxtender. ToString ()); } } "'
이 경우 '또는' GET 할 수 있느냐에 따라 게시물로의 포스트부퍼 널임 방관하겠나
진정한 성공은 '레스폰지아스트링' 의 경우 응답 됩니다
만약 성공 여부는 확인할 수 있습니다 ',' 거짓 '베베스스티언스테우스 하토프스테우스코드' 와 '레스폰지아스트링' 을 보려고 무엇이 문제인가.
난 아직 내가 모든 경우에 이 같은 의견을 닫히지만 시작 합니다.