Search code examples
c#.nethttpwebrequesthttpclienthttpwebresponse

How do I use HttpClient PostAsync parameters properly?


So I am working on writing an extension class for my project using HttpClient since I am moving over from HttpWebRequest.

When doing the POST request, how do I send a normal string as a parameter? No json or anything just a simple string.

And this is what it looks like so far.

static class HttpClientExtension
    {
        static HttpClient client = new HttpClient();
        public static string GetHttpResponse(string URL)
        {
            string fail = "Fail";
            client.BaseAddress = new Uri(URL);
            HttpResponseMessage Response = client.GetAsync(URL).GetAwaiter().GetResult();
            if (Response.IsSuccessStatusCode)
                return Response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            else
                return fail;
        }

        public static string PostRequest(string URI, string PostParams)
        {
            client.PostAsync(URI, new StringContent(PostParams));
            HttpResponseMessage response = client.GetAsync(URI).GetAwaiter().GetResult();
            string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            return content;
        }
    }

If you look at this like

client.PostAsync(URI, new StringContent(PostParams));

You can see that I just tried creating new StringContent and passing a string into it and the response returned 404 page not found. How do I properly use Post.Async(); do I send a string or byte array? Because with HttpWebRequest you would do it like this

public static void SetPost(this HttpWebRequest request, string postdata)
        {
            request.Method = "POST";
            byte[] bytes = Encoding.UTF8.GetBytes(postdata);

            using (Stream requestStream = request.GetRequestStream())
                requestStream.Write(bytes, 0, bytes.Length);
        }

Solution

  • In the PostRequest the following is done..

    client.PostAsync(URI, new StringContent(PostParams));
    HttpResponseMessage response = client.GetAsync(URI).GetAwaiter().GetResult();
    

    Which does not capture the response of the POST.

    Refactor to

    public static string PostRequest(string URI, string PostParams) {            
        var response = client.PostAsync(URI, new StringContent(PostParams)).GetAwaiter().GetResult();
        var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        return content;
    }
    

    HttpClient is primarily meant to be used async so consider refactoring to

    public static async Task<string> PostRequestAsync(string URI, string PostParams) {            
        var response = await client.PostAsync(URI, new StringContent(PostParams));
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }