Windows10环境下的Http20编程接口.docx

上传人:b****5 文档编号:30727826 上传时间:2023-08-19 格式:DOCX 页数:13 大小:58.59KB
下载 相关 举报
Windows10环境下的Http20编程接口.docx_第1页
第1页 / 共13页
Windows10环境下的Http20编程接口.docx_第2页
第2页 / 共13页
Windows10环境下的Http20编程接口.docx_第3页
第3页 / 共13页
Windows10环境下的Http20编程接口.docx_第4页
第4页 / 共13页
Windows10环境下的Http20编程接口.docx_第5页
第5页 / 共13页
点击查看更多>>
下载资源
资源描述

Windows10环境下的Http20编程接口.docx

《Windows10环境下的Http20编程接口.docx》由会员分享,可在线阅读,更多相关《Windows10环境下的Http20编程接口.docx(13页珍藏版)》请在冰豆网上搜索。

Windows10环境下的Http20编程接口.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 党团工作 > 入党转正申请

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1