Windows10环境下的Http20编程接口.docx
《Windows10环境下的Http20编程接口.docx》由会员分享,可在线阅读,更多相关《Windows10环境下的Http20编程接口.docx(13页珍藏版)》请在冰豆网上搜索。
![Windows10环境下的Http20编程接口.docx](https://file1.bdocx.com/fileroot1/2023-8/19/ffe4a62b-5b07-443c-9709-26a0cf006ec9/ffe4a62b-5b07-443c-9709-26a0cf006ec91.gif)
Windows10环境下的Http20编程接口
NOVEMBER23,20159:
27AM
DemystifyingHttpClientAPIsintheUniversalWindowsPlatform
By WindowsAppsTeam
SHARE TWEET SHARE SHARE SKYPE
AsaUniversalWindowsPlatform(UWP)appdeveloper,ifyouaretryingtocommunicateoverHTTPwithawebserviceoranyserverendpoint,youhavemultipleAPIchoices.TwoofthemostusedandrecommendedAPIsforimplementingtheHTTPclientroleinamanagedUWPappare System.Net.Http.HttpClient and Windows.Web.Http.HttpClient.TheseAPIsshouldbepreferredoverolder,discouragedAPIssuchasWebClientandHttpWebRequest(althoughasmallsubsetofHttpWebRequestisavailableinUWPforbackwardcompatibility).
WehavereceivedseveralquestionsaboutthedifferencesbetweentheseAPIs,equivalentfunctionalitiesbetweenthetwo,whichonetousewhen,andsoon.Inthispost,wewilltrytoaddressthesequestionsandhelpclarifythepurposeofthesetwoAPIs.
BriefOverview
TheSystem.Net.Http.HttpClientAPIwasfirstintroducedin.NET4.5,andavariantwasmadeavailableviaaNuGetpackagedown-levelfor.NET4.0andWindowsPhone8Silverlightapps.ThegoalofthisAPIwastoprovideasimpler,cleanerabstractionlayerandflexibilityforimplementingtheHTTPclientrole,ascomparedtotheolderHttpWebRequestAPI.Forexample,itallowschainingcustomhandlers,bywhichdeveloperscouldintercepteachrequestorresponse,andimplementcustomlogic.UpuntilWindows8.1,thisAPIhadafullymanaged.NETimplementationunderneath.InWindows10,theimplementationofthisAPIforUWPhasbeenchangedtolayeritontopofWindows.Web.HttpandtheWinINetHTTPstackofWindows.
Ontheotherhand,theWindows.Web.Http.HttpClientAPI,wasfirstintroducedinWindows8.1andwasavailableonWindowsPhone8.1aswell.TheprimarymotivationbehindcreatingthisAPIwastoconsolidatethedisparateHTTPAPIsavailablefordifferentWindowsapplanguages(C#,VB,C++,JavaScript)intoasingleonethatsupportsallthefeaturesfromeachofthoseAPIs.MostofthebasicAPIdesignwasderivedfromthatofSystem.Net.HttpandtheimplementationisbasedontheWinINetHTTPstackofWindows.
WhenusingtheseAPIsinaWindowsStoreapp,thesupportedOSversionsandprogramminglanguagesareasfollows:
API
OSVersions
SupportedLanguages
System.Net.Http.HttpClient
Windows,WindowsPhone8onwards
.NETlanguagesonly
Windows.Web.Http.HttpClient
Windows,WindowsPhone8.1onwards
AllWindowsStoreapplanguages
WhichoneshouldIuse?
SincebothoftheseAPIsareavailableinUWP,thebiggestquestionforHTTPdevelopersiswhichonetouseintheirapp.Theansweristhatitdependsonacoupleoffactors:
1.DoyouneedtointegratewithnativeUIforcollectingusercredentials,controlHTTPcachereadandwritebehavior;orpassinaspecificSSLclientcertificateforauthentication?
Ifyes–thenuseWindows.Web.Http.HttpClient.Atthetimeofthiswriting,theWindows.Web.HttpAPIprovidesgreatercontroloverHTTPsettingsinUWPthantheSystem.Net.HttpAPI.Infutureversions,theSystem.Net.HttpAPImayalsobeenhancedtosupportthesefeaturesonUWP.
2.Doyouintendtowritecross-platform.NETcode(acrossUWP/ASP.NET5/iOSandAndroid)?
Ifyes–thenuseSystem.Net.HttpAPI.Thisallowsyoutowritecodethatyoucanre-useonother.NETplatformssuchasASP.NET5and.NETFrameworkdesktopapplications.Thanksto Xamarin,thisAPIisalsosupportedoniOSandAndroid,soyoucanreuseyourcodeontheseplatformsaswell.
ObjectModel
NowthatweunderstandthemotivationbehindcreatingthesetwosimilarAPIsandtherationaleforchoosingbetweenthetwo,let’slookcloserattheobjectmodelforeachofthese.
System.Net.Http
Thetopmostabstractionlayeristhe HttpClient object,whichrepresentsthecliententityintheclient-servermodeloftheHTTPprotocol.Thisclientcanissuemultiplerequests(representedby HttpRequestMessage)totheserverandreceivethecorrespondingresponses(representedby HttpResponseMessage).TheentitybodyandcontentheadersofeachHTTPrequestorresponseisrepresentedbythe HttpContent baseclass,andderivedclassessuchasStreamContent,MultipartContentandStringContent.TheyprovidedifferentrepresentationsoftheHTTPentitybody.EachoftheseclassesprovideasetofReadAs*methodstoreadouttheentitybodyofarequestorresponseasastring,bytearrayorastream.
EachHttpClientobjecthasahandlerobjectunderneaththatrepresentsalltheHTTP-relatedsettingsofthatclient.Conceptually,youcanthinkofthehandlerasrepresentingtheHTTPstackunderneaththeclient.Itisresponsibleforsendingtheclient’sHTTPrequeststotheserverandconveyingtheresponsebacktotheclient.
ThedefaulthandlerclassusedintheSystem.Net.HttpAPIis HttpClientHandler.WhenyoucreateanewinstanceofanHttpClientobject—forexample,callnewHttpClient()—anHttpClientHandlerobjectisautomaticallycreatedforyouwiththedefaultHTTPstacksettings.Ifyouwanttomodifyanyofthedefaultsettingssuchascachingbehavior,automaticcompression,credentialsorproxy,youcancreateyourowninstanceofanHttpClientHandlerdirectly,modifyitspropertiesandthenpassitintotheconstructorofHttpClient,asfollows:
1
2
3
HttpClientHandlermyHandler=newHttpClientHandler();
myHandler.AllowAutoRedirect=false;
HttpClientmyClient=newHttpClient(myHandler);
ChainingofHandlers
OneofthekeyadvantagesoftheSystem.Net.Http.HttpClientAPIdesignistheabilitytoinsertcustomhandlersandcreateachainofhandlerobjectsunderneathanHttpClientobject.Forexample,let’ssayyouarebuildinganappthatqueriesawebserviceforsomedata.YouhavecustomlogictohandleHTTP4xx(clienterror)and5xx(servererror)responsesfromtheserverandwanttotakespecificretrysteps,suchastryingadifferentendpointoraddingusercredentials.YouwouldideallywanttoseparatethisHTTP-relatedworkfromtherestofyourbusinesslogicwhichjustcaresaboutthedatareturnedfromthewebservice.
Thiscanbeachievedbycreatinganewhandlerclassthatderivesfromthe DelegatingHandler class(e.g.CustomHandler1),thencreateanewinstanceofitandpassthatintotheHttpClientconstructor.TheInnerHandlerpropertyoftheDelegatingHandlerclassisusedtospecifythenexthandlerinthechain–forexample,youcouldaddanothercustomhandler(e.g.CustomHandler2)tothechain.Forthelasthandler,youcansettheinnerhandlertoanHttpClientHandlerinstance–thiswillpasstherequestontotheHTTPstackoftheOS.Here’showthislooksconceptually:
Andhereisthesamplecodetoachievethis:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
publicclassCustomHandler1:
DelegatingHandler
{
//Constructorsandothercodehere.
protectedasyncoverrideTaskSendAsync(
HttpRequestMessagerequest,CancellationTokencancellationToken)
{
//ProcesstheHttpRequestMessageobjecthere.
Debug.WriteLine("ProcessingrequestinCustomHandler1");
//Onceprocessingisdone,callDelegatingHandler.SendAsynctopassitonthe
//innerhandler.
HttpResponseMessageresponse=awaitbase.SendAsync(request,cancellationToken);
//ProcesstheincomingHttpResponseMessageobjecthere.
Debug.WriteLine("ProcessingresponseinCustomHandler1");
returnresponse;
}
}
publicclassCustomHandler2:
DelegatingHandler
{
//SimilarcodeasCustomHandler1.
}
publicclassFoo
{
publicvoidCreateHttpClientWithChain()
{
HttpClientHandlersystemHandler=newHttpClientHandler();
CustomHandler1myHandler1=newCustomHandler1();
CustomHandler2myHandler2=newCustomHandler2();
//Chainthehandlerstogether.
myHandler1.InnerHandler=myHandler2;
myHandler2.InnerHandler=systemHandler;
//Createtheclientobjectwiththetopmosthandlerinthechain.
HttpClientmyClient=newHttpClient(myHandler1);
}
}
Notes:
1.Ifyouintendtosendtherequesttoaremoteserverendpoint,thelastHandlerinachainistypicallyHttpClientHandler,whichactuallysendstherequestoutonthewireandreceivetheresponsefromtheHTTPstackoftheOS.Alternatively,youcoulduseamockhandlerthatpretendstobetheserverandreturnsfabricatedresponses.
2.Addingprocessinglogicinthehandlerbeforepassingtherequesttotheinnerhandlerortheresponsetotheupperhandlercanleadtoperformanceloss.Itisbesttoavoidexpensivesynchronousoperationsinthisscenario.
FormoredetailsontheconceptofchainingHandlers,see thispost byHenrikNielsen(NotethatitreferstotheASP.NETWebAPIversionoftheAPI,whichisslightlydifferentfromthe.NETframeworkonediscussedhere.Theconceptofchaininghandlersiscommonthough.)
Windows.Web.Http
TheobjectmodelfortheWindows.Web.HttpAPIisverysimilartothatoftheSystem.Net.Httpversiondescribedabove–italsohastheconceptofacliententity,ahandler(called“filter”inthisnamespace)andtheoptionofinsertingcustomlogicbetweentheclientandthesystem-defaultfilter.
MostofthetypesaredirectanalogsofthetypesintheSystem.Net.Httpobjectmodel,asfollows:
HTTPclientroleaspect
System.Net.Httptype
CorrespondingWindows.Web.Httptype
Cliententity
HttpClient
HttpClient
HTTPrequest
HttpRequestMessage
HttpRequestMessage
HTTPresponse
HttpResponseMessage
HttpResponseMessage
EntitybodyofanHTTPrequestorresponse
HttpContent
IHttpContent
Represent