350 likes | 550 Views
Five great reasons to use the new HttpClient API. Peter Smith Program Manager 4-092. 5 top reasons to use the new HttpClient API. C++. C#. JavaScript. Reason. new!. ✔. ✔. Shared cache, cookies, credentials. new!. new!. ✔. Strongly typed headers=fewer bugs in less time. new!.
E N D
Five great reasons to use the new HttpClient API Peter Smith Program Manager 4-092
5 top reasons to use the new HttpClient API C++ C# JavaScript Reason new! ✔ ✔ Shared cache, cookies, credentials new! new! ✔ Strongly typed headers=fewer bugs in less time new! new! ✔ Access to cookies and shared cookies new! new! new! Control over caching and shared cache new! ✔ new! Inject your code modules into the processing pipeline=cleaner, more modular code
Meet the family! HttpClient (has common send methods) Http Base Protocol Filter (has in-depth settings) Your App REST/Web Service HttpRequestMessage HttpResponseMessage ⛭ HttpContent String • Stream • Buffer • Multipart • FormUrlEncoded
Simple example • try • { • var uri = newUri("http://example.com/datalist.aspx"); • var httpClient = newHttpClient(); • var result = await httpClient.GetStringAsync(uri); • } • catch (Exception e) • { • }
Cache, cookies, credentials are already shared between <WebView>, <Image>, <Media>, …These shared with Windows.Web.Http, too(but not shared across apps)
Strongly typed headers • Headers are easy to mistype • The errors are hard to spot • Even big sites make mistakes • Pramga:no-cache • LastModified:Fri, 08 Mar 2013 19:26:00 GMT • Cneonction:close • ntCoent-Length:190946
Host • // HostName is part of the Windows.Networking namespace. • var request = newHttpRequestMessage(); • request.Headers.Host = newHostName("contoso.com");
Content-Length • ulong len = response.Content.Headers.ContentLength.Value; • byte[] buffer = newbyte[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 = newHttpBaseProtocolFilter(); • var cookieManager = bpf.CookieManager; • var cookie = newHttpCookie("myCookieName", ".example.com", "/"); • cookie.Value = "myValue"; • cookieManager.SetCookie(cookie); • // Use this base protocol file with an HttpClient • var httpClient = newHttpClient(bpf);
Where did my data come from? • var httpResponse = awaithttpClient.GetAsync(uri); • switch(httpResponse.Source) • { • caseHttpResponseMessageSource.Cache: break; • caseHttpResponseMessageSource.Network: break; • caseHttpResponseMessageSource.None: break; • }
Cache write behavior • var bpf = newHttpBaseProtocolFilter(); • // Set the WriteBehavior. • bpf.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default; • bpf.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; • // Use the base protocol filter in an HttpClient • var hc = newHttpClient(bpf);
Cache read behavior • var bpf = newHttpBaseProtocolFilter(); • // 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 = newHttpClient(bpf);
Reason #5:The HTTP Processing pipeline includes your filter code
Remember this diagram? HttpClient (has common send methods) Http Base Protocol Filter (has in-depth settings) Your App REST/Web Service HttpRequestMessage HttpResponseMessage ⛭ HttpContent String • Stream • Buffer • Multipart • FormUrlEncoded
The filter pipeline HttpClient (has common send methods) 503 Retry Filter Metered Network Filter Auth Filter Http Base Protocol Filter (has in-depth settings) Your App REST/Web Service HttpRequestMessage ⛭ HttpResponseMessage HttpContent String • Stream • Buffer • Multipart • FormUrlEncoded
IHttpFilters • Filters are for: • Auth • Custom caches • Logging • Network Restrictions • Retry • Testing • Filters are WinRT Components • They implement Windows.Web.Http.Filters.IHttpFilter • It’s just one method: SendRequestAsync (+dispose) • You put them into the filter pipeline • Most pipelines end with a HttpBaseProtocolFilter • Each filter sees all requests going out • And all responses coming back • And can modify them
Recap HttpClient Delete GetPost Put SendRequestAsync DefaultRequestHeaders 503 Retry Filter Metered Network Filter Auth Filter Http Base Protocol Filter REST/Web Service Your App HttpRequestMessage HttpResponseMessage HttpContent String • Stream • Buffer • Multipart • FormUrlEncoded
5 top reasons to use the new HttpClient API C++ C# JavaScript Reason new! ✔ ✔ Shared cache, cookies, credentials new! new! ✔ Strongly typed headers=fewer bugs in less time new! new! ✔ Access to cookies and shared cookies new! new! new! Control over caching and shared cache new! ✔ new! Inject your code modules into the processing pipeline=cleaner, more modular code
Reasons 6 and up… • HttpProgress • SSL/TLS errors/certificates (including stronger security) • Streaming uploads & Streaming downloads • Additional settings on HttpBaseProtocolFilter • Make your own IHttpContent & IHttpFilter classes • Configuring the OAuth 2.0 filter • Server/Proxy credentials • Client certificate
How to get started • 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
Resources • 3-090: Building great service connected apps • 3-113: Building a great authentication experience into your app • //build/ 2011 • PLAT-785T: Creating connected apps that work on today’s networks • Windows app developer blog • April 10, 2013: Creating connected Windows Store apps
What to do next? • Find and use filters • Make and share filters • Update your code to use the new classes
Required Slide *delete this box when your slide is finalized Your MS Tag will be inserted here during the final scrub. Evaluate this session • Scan this QR codeto evaluate this session and be automatically entered in a drawing to win a prize!