Windows10环境下的Http20编程接口.docx
- 文档编号:30727826
- 上传时间:2023-08-19
- 格式:DOCX
- 页数:13
- 大小:58.59KB
Windows10环境下的Http20编程接口.docx
《Windows10环境下的Http20编程接口.docx》由会员分享,可在线阅读,更多相关《Windows10环境下的Http20编程接口.docx(13页珍藏版)》请在冰豆网上搜索。
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.
protectedasyncoverrideTask
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Windows10 环境 Http20 编程 接口
![提示](https://static.bdocx.com/images/bang_tan.gif)