Home > Uncategorized > Support #HTTP2 in your C# Client code

Support #HTTP2 in your C# Client code

http2

If you use code such as WebClient to make HTTP requests from C#, then you’re probably using HTTP 1.1. if you want to use HTTP/2 then you need to write some extra code.

First, let’s prove that you’re using HTTP 1.1

WebClient wc = new WebClient();
var check1 = wc.DownloadString(“https://http2.pro/api/v1”);

and the response is

{“http2″:0,”protocol”:”HTTP\/1.1″,”push”:0,”user_agent”:””}

Now, to use HTTP 2, you need to override a setting here;

public class Http2CustomHandler : WinHttpHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
request.Version = new Version(“2.0”);
return base.SendAsync(request, cancellationToken);
}
}

And we can make a GET request like so;

public static string GetHtmlFromUrl(string Url)
{
var httpClient = new HttpClient(new Http2CustomHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
var resTask = httpClient.GetAsync(new Uri(Url));
var response = resTask.Result;
var strTask = response.Content.ReadAsStringAsync();
var strResponse = strTask.Result;
return strResponse;
}

And check again;

var check2 = GetHtmlFromUrl(“https://http2.pro/api/v1&#8221;);

Which yields

{“http2″:1,”protocol”:”HTTP\/2.0″,”push”:0,”user_agent”:””}

Hope this helps!

 

 

 

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: