2016-08-05 3 views
1

헤더와 내용을 함께 사용하여 postAsync해야합니다. C#의 콘솔 응용 프로그램을 통해 웹 사이트에 액세스하려면 나는 HttpHeader 변수 이름 헤더를 가진 객체와 __Token, return, EmailPassword 인 문자열 객체로 newContent이라는 내용을 가지고 있습니다. 이제는 헤더에 newContent를 추가 한 다음 postAsync(url, header+content)을 사용하여 POST 요청을 작성합니다.postAsync with header and content C#

public async static void DownloadPage(string url) 
{ 
    CookieContainer cookies = new CookieContainer(); 
    HttpClientHandler handler = new HttpClientHandler(); 
    handler.CookieContainer = cookies; 

    using (HttpClient client = new HttpClient(handler)) 
    { 
     using (HttpResponseMessage response = client.GetAsync(url).Result) 
     { 
      //statusCode 
      CheckStatusCode(response); 
      //header 
      HttpHeaders headers = response.Headers; 
      //content 
      HttpContent content = response.Content; 
      //getRequestVerificationToken&createCollection 
      string newcontent = CreateCollection(content); 

      using(HttpResponseMessage response2 = client.PostAsync(url,)) 

     } 

    } 
} 

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); 
} 


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("return", ""); 
    collection.Add("Email", "[email protected]"); 
    collection.Add("Password", "1234"); 
    var newCollection = GenerateQueryString(collection); 
    return newCollection; 
} 
+0

무엇을 의미합니까? 나는 그것을하는 법을 모르겠습니다 ... @x ... – Puzzle

답변

1

나는 어제 같은 일을했다. 내 콘솔 응용 프로그램을위한 별도의 클래스를 만들고 거기에 HttpClient 물건을 넣어. 홈페이지에서

:

_httpCode = theClient.Post (_response, theClient.auth_bearer_token); 클래스에서

:

public long Post_RedeemVoucher(Response _response, string token) 
    { 
     string client_URL_voucher_redeem = "https://myurl"; 

     string body = "mypostBody"; 

     Task<Response> content = Post(null, client_URL_voucher_redeem, token, body); 

     if (content.Exception == null) 
     { 
      return 200; 
     } 
     else 
      return -1; 
    } 

그런 다음 호출 자체 :

async Task<Response> Post(string headers, string URL, string token, string body) 
    { 
     Response _response = new Response(); 

     try 
     { 
      using (HttpClient client = new HttpClient()) 
      { 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

       HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL); 
       request.Content = new StringContent(body); 

       using (HttpResponseMessage response = await client.SendAsync(request)) 
       { 
        if (!response.IsSuccessStatusCode) 
        { 
         _response.error = response.ReasonPhrase; 
         _response.statusCode = response.StatusCode; 

         return _response; 
        } 

        _response.statusCode = response.StatusCode; 
        _response.httpCode = (long)response.StatusCode; 

        using (HttpContent content = response.Content) 
        { 
         _response.JSON = await content.ReadAsStringAsync().ConfigureAwait(false); 
         return _response; 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      _response.ex = ex; 
      return _response; 
     } 
    } 

나는이 당신 포인트 그가 올바른 방향으로 바랍니다!

var content = new StringContent(requestString, Encoding.UTF8); 

// Iterate over current headers, as you can't set `Headers` property, only `.Add()` to the object. 
foreach (var header in httpHeaders) { 
    content.Headers.Add(header.Key, header.Value.ToString()); 
} 

response = client.PostAsync(Url, content).Result; 

을 지금, 그들은 하나의 방법으로 전송하고 있습니다 : 당신의 Headers 반복하고 Content 객체에 추가 대해 어떻게

+0

대단히 감사합니다. 나는 집으로 돌아가서 어떻게되는지 알려 줄 것이다. – Puzzle

+0

나야 아니면 너의 머리글 @GrahamJ을 절대 사용하지 말아라. – Puzzle

1

.

+0

니스 나는 내가 집에 돌아와서 어떻게되는지 알려줄거야 .l – Puzzle

+0

너 그런 "헤더"를 추가 할 수 없다 ... 나는 더 나은 방법을 찾을 수 없었다 ... – Puzzle

+0

하나는 "헤더"를 추가 할 수 없다 ... 나는 header.key를 사용하여 이름을 시도하고 header.value.Tostring()에 대한 값은 작동하지 않습니다. 그것은 다음과 같은 오류 헤더 이름을 잘못 사용했다. 요청 헤더가 HttpRequestMessage, HttpResponseMessage가있는 응답 헤더 및 HttpContent 개체가있는 내용 헤더와 함께 사용되는지 확인하십시오. – Puzzle

0

아직이 문제를 조사하고있는 경우 요청 수준뿐 아니라 HttpClient 수준의 헤더를 추가 할 수도 있습니다. 이 작품은 나를 위해 :

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL); 

request.Content = new StringContent(body); 

request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); 
+0

쿠키는 어떻게됩니까? 내 getAsync에서 얻은 쿠키로 요청을 게시 할 수 없습니다 ... – Puzzle