5 top reasons to use the new HttpClient API
Reason
C++
1. Shared cache, cookies, credentials
✔
2. Strongly typed headers=fewer bugs in less time
new!
3. Access to cookies and shared cookies
4. Control over caching and shared cache
5. Inject your code modules into the processing
pipeline=cleaner, more modular code
✔
C#
JavaScript
new!
✔
✔
new!
new! new!
new! new! new!
new!
✔
new!
⛭
Simple example
try
{
var uri = new Uri("http://example.com/datalist.aspx");
var httpClient = new HttpClient();
var result = await httpClient.GetStringAsync(uri);
}
catch (Exception e)
{
}
Host
// HostName is part of the Windows.Networking namespace.
var request = new HttpRequestMessage();
request.Headers.Host = new HostName("contoso.com");
Content-Length
ulong len = response.Content.Headers.ContentLength.Value;
byte[] buffer = new byte[len];
Last-Modified
DateTimeOffset d = response.Content.Headers.LastModified.Value;
Setting a custom header
// Add a custom header to the request.
request.Headers.TryAppendWithoutValidation
("X-Requested-With", "XMLHttpRequest");
List all headers
// List all the headers in the response and response.Content.
foreach (var header in httpResponse.Headers)
{
Log (header.Key + "=" + header.Value);
}
foreach (var header in httpResponse.Content.Headers)
{
Log (header.Key + "=" + header.Value);
}
How to set a cookie
var bpf = new HttpBaseProtocolFilter();
var cookieManager = bpf.CookieManager;
var cookie = new HttpCookie("myCookieName", ".example.com", "/");
cookie.Value = "myValue";
cookieManager.SetCookie(cookie);
// Use this base protocol file with an HttpClient
var httpClient = new HttpClient(bpf);
Where did my data come from?
var httpResponse = await httpClient.GetAsync(uri);
switch (httpResponse.Source)
{
case HttpResponseMessageSource.Cache: break;
case HttpResponseMessageSource.Network: break;
case HttpResponseMessageSource.None: break;
}
Cache write behavior
var bpf = new HttpBaseProtocolFilter();
// Set the WriteBehavior.
bpf.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;
bpf.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
// Use the base protocol filter in an HttpClient
var hc = new HttpClient(bpf);
Cache read behavior
var bpf = new HttpBaseProtocolFilter();
// Set the ReadBehavior.
bpf.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default;
bpf.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
bpf.CacheControl.ReadBehavior = HttpCacheReadBehavior.OnlyFromCache;
// Use the base protocol filter in an HttpClient
var hc = new HttpClient(bpf);
⛭
⛭
5 top reasons to use the new HttpClient API
Reason
C++
1. Shared cache, cookies, credentials
✔
2. Strongly typed headers=fewer bugs in less time
new!
3. Access to cookies and shared cookies
4. Control over caching and shared cache
5. Inject your code modules into the processing
pipeline=cleaner, more modular code
✔
C#
JavaScript
new!
✔
✔
new!
new! new!
new! new! new!
new!
✔
new!
© Copyright 2026 Paperzz