0
C#으로 PostAsync 요청을 만들려고합니다. 다음은 내 코드입니다.httpclient header + content joined PostAsyn
static void Main(string[] args)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage getResponse = client.GetAsync("http://google.com").Result)
{
CheckStatusCode(getResponse);
String header = getResponse.Headers.ToString();
var content = CreateCollection(getResponse.Content);
var _stringHeaderContent = header + "\r" + content;
HttpContent _content = new StringContent(_stringHeaderContent, Encoding.UTF8);
Console.WriteLine(_content);
using (HttpResponseMessage postResponse = client.PostAsync("http://google.com",_content).Result)
{
Console.WriteLine(postResponse.Headers);
CheckStatusCode(postResponse);
Console.WriteLine(postResponse.Headers);
}
}
}
}
방법 :
public static void CheckStatusCode(HttpResponseMessage response)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.ReasonPhrase));
else
Console.WriteLine("200");
}
public static String CreateCollection(HttpContent content)
{
var myContent = content.ReadAsStringAsync().Result;
HtmlNode.ElementsFlags.Remove("form");
string html = myContent;
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var input = doc.DocumentNode.SelectSingleNode("//*[@name='__Token']");
var token = input.Attributes["value"].Value;
//add all necessary component to collection
NameValueCollection collection = new NameValueCollection();
collection.Add("__Token", token);
collection.Add("returnURL", "");
collection.Add("Email", "[email protected]");
collection.Add("Password", "1234");
String queryString = GenerateQueryString(collection);
return queryString;
}
public static string GenerateQueryString(NameValueCollection collection)
{
var array = (from key in collection.AllKeys
from value in collection.GetValues(key)
select string.Format("{0}={1}", WebUtility.UrlEncode(key), WebUtility.UrlEncode(value))).ToArray();
return string.Join("&", array);
}
이 코드와 데 문제가 아무것도 _content에 저장되지됩니다. 나는 머리글과 내용의 일부가 조인 된 postAsync 요청을 만들려고합니다. 그러나 postAsync 요청을하면 _content에 아무 것도 저장되지 않습니다. 따라서 요청이 실패합니다.
누구나 _stringHeaderContent로 postAsync 요청을 만들 수있는 방법을 설명 할 수 있습니까?
감사
가 어떻게 쿠키 과거에 합격 할 수 있습니까? – Puzzle
보기 : http://stackoverflow.com/questions/12373738/how-do-i-set-a-cookie-on-httpclients-httprequestmessage –