놀랍게도 .NET BCL에서 알 수있는 것에서 이와 같이 간단한 것을 할 수는 없습니다.
byte[] response = Http.Post
(
url: "http://dork.com/service",
contentType: "application/x-www-form-urlencoded",
contentLength: 32,
content: "home=Cosby&favorite+flavor=flies"
);
위의이 가상 코드는 데이터를 사용하여 HTTP POST를 만들고 Post
정적 클래스 의 메서드에서 응답을 반환합니다 Http
.
우리에게는이 쉬운 일이 남지 않았으므로 차선책은 무엇입니까?
데이터와 함께 HTTP POST를 보내고 응답 내용을 얻으려면 어떻게해야합니까?
답변
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues("http://dork.com/service", new NameValueCollection()
{
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});
string result = System.Text.Encoding.UTF8.GetString(response);
}
다음이 포함되어야합니다.
using System;
using System.Collections.Specialized;
using System.Net;
정적 메소드 / 클래스를 사용하지 않는 경우 :
public static class Http
{
public static byte[] Post(string uri, NameValueCollection pairs)
{
byte[] response = null;
using (WebClient client = new WebClient())
{
response = client.UploadValues(uri, pairs);
}
return response;
}
}
그런 다음 간단히 :
var response = Http.Post("http://dork.com/service", new NameValueCollection() {
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});
답변
HttpClient를 사용하면 Windows 8 앱 개발과 관련 하여이 문제가 발생했습니다.
var client = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("pqpUserName", "admin"),
new KeyValuePair<string, string>("password", "test@123")
};
var content = new FormUrlEncodedContent(pairs);
var response = client.PostAsync("youruri", content).Result;
if (response.IsSuccessStatusCode)
{
}
답변
WebRequest를 사용하십시오 . 에서 스콧 Hanselman은 :
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
답변
private void PostForm()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dork.com/service");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData ="home=Cosby&favorite+flavor=flies";
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
stream.Dispose();
reader.Dispose();
}
답변
개인적으로 http 게시를 수행하고 응답을 얻는 가장 간단한 방법은 WebClient 클래스를 사용하는 것입니다. 이 클래스는 세부 사항을 훌륭하게 추상화합니다. MSDN 문서에는 전체 코드 예제도 있습니다.
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx
귀하의 경우에는 UploadData () 메소드가 필요합니다. (또, 코드 샘플이 설명서에 포함되어 있습니다)
http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx
UploadString ()도 잘 작동하며 한 단계 더 추상화합니다.
http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx
답변
나는 이것이 오래된 실이라는 것을 알고 있지만 그것이 어느 정도 도움이되기를 바랍니다.
public static void SetRequest(string mXml)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
webRequest.Method = "POST";
webRequest.Headers["SOURCE"] = "WinApp";
// Decide your encoding here
//webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentType = "text/xml; charset=utf-8";
// You should setContentLength
byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
webRequest.ContentLength = content.Length;
var reqStream = await webRequest.GetRequestStreamAsync();
reqStream.Write(content, 0, content.Length);
var res = await httpRequest(webRequest);
}
답변
다른 답변이 몇 살인 것을 감안할 때 현재 도움이 될만한 내 생각은 다음과 같습니다.
가장 간단한 방법
private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
var client = new HttpClient();
var response = await client.PostAsync(uri, dataOut);
return await response.Content.ReadAsStringAsync();
// For non strings you can use other Content.ReadAs...() method variations
}
보다 실용적인 예
알려진 유형과 JSON을 다루는 경우가 많으므로 다음과 같은 여러 구현으로이 아이디어를 더 확장 할 수 있습니다.
public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var results = await PostAsync(uri, content); // from previous block of code
return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}
이것이 어떻게 호출 될 수 있는지의 예 :
var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);
