2016-08-05 5 views
1

Мне нужно postAsync с заголовком и контентом вместе. Чтобы получить доступ к веб-сайту через консольное приложение на C#. У меня есть мои заголовки как объект HttpHeader с заголовком переменной имени, а мой контент с именем newContent в виде строкового объекта с __Token, return, Email и Password. Теперь я хочу добавить newContent в заголовок, а затем использовать postAsync(url, header+content), чтобы выполнить мой запрос POST.postAsync с заголовком и содержимым 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.

В Main:

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

Я надеюсь, что это указывает вам в правильном направлении, он!

+0

Большое спасибо. Я попробую, как только я вернусь домой и дам вам знать, как это происходит :) – Puzzle

+0

Является ли это я, или вы никогда не используете свой заголовок @GrahamJ – Puzzle

1

Как насчет итерацию над Headers и добавить их к Content объекта:

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; 

Теперь они послали в одном методе.

+0

Ницца Я попробую, когда вернусь домой и дам вам знать, как это происходит. – Puzzle

+0

You не могу добавить «заголовок», как это ... Я не мог найти лучший способ ... – 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

Как насчет печенья? Я не могу отправить запрос с помощью файлов cookie, которые я получаю от моего getAsync ... – Puzzle