postAsync with header and content c#

Puzzle picture Puzzle · Aug 5, 2016 · Viewed 17k times · Source

I need to postAsync with header and content together. In order to get access to a website through Console Application in C#. I have my headers as an HttpHeader object with variable name header and my content named newContent as a string object with __Token, return, Email and Password. Now what I want to do is add newContent to header and then use postAsync(url, header+content) to make my POST request.

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

Answer

GrahamJ picture GrahamJ · Aug 5, 2016

I did the very same thing yesterday. I created a seperate class for my Console App and put the HttpClient stuff in there.

In Main:

_httpCode = theClient.Post(_response, theClient.auth_bearer_token);

In the class:

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

Then the call itself:

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

I hope this points you in he right direction!