A very simple "Using C# HttpClient from Sync and Async code"

Simplicity is so nice. I just spent two hours zooming all over the web looking for a very simple HTTPClient code sample. Of dozens that I saw, all of them were overcomplicated. I knew it was just a matter of a few lines of code, and couldn't believe the poor quality and needless complexity I was seeing. The most promising alternative to HTTPClient, for example, RestSharp, currently has code samples which do not match the actual code, which is unfortunate because it does look like the best way to go. I'm not trying to debug someone else's project, I'm simply looking for the easiest way to get up and running with parsing JSON data from a REST endpoint.

Finally, I found this brief post: Using C# HttpClient from Sync and Async code.

It's exactly what I'm looking for. Why did it take two hours to find? Because too few people are linking to it. So this post is my link to it, to make it easier for others to find. Thank you Brian.

Here's the most useful part, follow the link for the rest:

private static readonly HttpClient _httpClient= new HttpClient();

public static async Task Get(string queryString)
  string authUserName = "user";
  string authPassword = "password";
  string url = "https://someurl.com";

  // If you do not have basic authentication, you may skip these lines
  var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}");
  _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

  // The actual Get method
  using (var result = await _httpClient.GetAsync($"{url}{queryString}"))
    string content = await result.Content.ReadAsStringAsync();
    return content;

Oh, wait! This is what I was looking for, even more simple:


Here's what I ended up with. Works great:

private string HttpGet(string authUserName, string authPassword, string url, string queryString = "")
    // ignore certificate error, a little bit of broadsword+shotgun here.
    // go here for nicer ways of doing this same thing:
    // https://stackoverflow.com/questions/1301127/how-to-ignore-a-certificate-error-with-c-sharp-2-0-webclient-without-the-certi
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

    string got = "";

    using (var client = new WebClient())
        var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}");
        client.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(authToken));
        client.Headers.Add("Accept", "application/json");
        client.Headers.Add("Content-Type", "application/json; charset=utf-8");

        got = client.DownloadString($"{url}{queryString}");

    return got;

Posted in Everything on Oct 08, 2018