Five great reasons to use the new HttpClient API
description
Transcript of Five great reasons to use the new HttpClient API
Five great reasons to use the new HttpClient API
Peter SmithProgram Manager4-092
5 top reasons to use the new HttpClient API
Reason C++ C# JavaScript
1. Shared cache, cookies, credentials ✔2. Strongly typed headers=fewer bugs in less time
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
✔new!
✔ new! new!
new! ✔ new!
new! ✔ new!
new! new! new!
REST/Web Service
HttpClient(has common
send methods)
Meet the family!Your App
HttpRequestMessage
HttpResponseMessage
Http Base Protocol
Filter(has in-depth
settings)
HttpContentString • Stream • Buffer
• Multipart • FormUrlEncoded
⛭
Simple exampletry{ var uri = new Uri("http://example.com/datalist.aspx"); var httpClient = new HttpClient(); var result = await httpClient.GetStringAsync(uri);}catch (Exception e){}
Let’s see it in action!
Reason #1:
HTTP Integration: cache, cookies, credentials…
Cache, cookies, credentials are already shared between <WebView>, <Image>, <Media>, …
These shared with Windows.Web.Http, too
(but not shared across apps)
Reason #2:
Strongly typed headers: fewer bugs in less time
Pramga:no-cacheLastModified:Fri, 08 Mar 2013 19:26:00 GMTCneonction:closentCoent-Length:190946
Headers are easy to mistype
The errors are hard to spot
Even big sites make mistakes
Strongly typed headers
Host// HostName is part of the Windows.Networking namespace.var request = new HttpRequestMessage();request.Headers.Host = new HostName("contoso.com");
Content-Lengthulong 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); }
Reason #3:
list, set and delete cookies
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);
Let’s see it in action!
Reason #4:
Influence over the system network cache
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 behaviorvar bpf = new HttpBaseProtocolFilter();
// Set the WriteBehavior.bpf.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;bpf.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
// Use the base protocol filter in an HttpClientvar hc = new HttpClient(bpf);
Cache read behaviorvar 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 HttpClientvar hc = new HttpClient(bpf);
Reason #5:
The HTTP Processing pipeline includes your filter code
REST/Web Service
HttpClient(has common
send methods)
Remember this diagram?
Your App
HttpRequestMessage
HttpResponseMessage
Http Base Protocol
Filter(has in-depth
settings)
HttpContentString • Stream • Buffer
• Multipart • FormUrlEncoded
⛭
Auth Filter
503 Retry Filter
Metered Network Filter
REST/Web Service
HttpClient(has common
send methods)
The filter pipeline
Your App
HttpRequestMessageHttpResponseMess
age
Http Base Protocol
Filter(has in-depth
settings)
HttpContentString • Stream • Buffer
• Multipart • FormUrlEncoded
⛭
Let’s see it in action!
Filters are WinRT ComponentsThey implement Windows.Web.Http.Filters.IHttpFilterIt’s just one method: SendRequestAsync (+dispose)You put them into the filter pipelineMost pipelines end with a HttpBaseProtocolFilterEach filter sees all requests going outAnd all responses coming backAnd can modify them
Filters are for:AuthCustom cachesLoggingNetwork RestrictionsRetryTesting
IHttpFilters
REST/Web Service
Auth Filter
503 Retry Filter
Metered Network Filter
Recap
HttpClientDelete Get Post Put SendRequestAsync
DefaultRequestHeaders
Your App
HttpRequestMessage
Http Base
Protocol Filter
HttpContentString • Stream • Buffer
• Multipart • FormUrlEncoded
HttpResponseMessage
5 top reasons to use the new HttpClient API
Reason C++ C# JavaScript
1. Shared cache, cookies, credentials ✔2. Strongly typed headers=fewer bugs in less time
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
✔new!
✔ new! new!
new! ✔ new!
new! ✔ new!
new! new! new!
HttpProgressSSL/TLS errors/certificates (including stronger security)Streaming uploads & Streaming downloadsAdditional settings on HttpBaseProtocolFilterMake your own IHttpContent & IHttpFilter classesConfiguring the OAuth 2.0 filterServer/Proxy credentialsClient certificate
Reasons 6 and up…
HttpClient sample has lots of code and the metered network filter and the 503 retry filter
Web Authorization Broker sample has an OAuth 2.0 filter
MSDN documentation (look under Windows.Web.Http)
MSDN Windows Store apps forums
How to get started
Resources3-090: Building great service connected apps3-113: Building a great authentication experience into your app
//build/ 2011PLAT-785T: Creating connected apps that work on today’s networks
Windows app developer blogApril 10, 2013: Creating connected Windows Store apps
What to do next?Find and use filtersMake and share filtersUpdate your code to use the new classes
Evaluate this session
Scan this QR code to evaluate this session and be automatically entered in a drawing to win a prize!
© 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.