/// <summary> ///Http GET Request/// </summary> /// <param name= "url" >Request Address</param> /// <param name= "PostData" >Request Parameters</param> /// <param name= "Result" >return Results</param> /// <returns></returns> Public Static BOOLWebhttpget (stringUrlstringPostData, out stringresult) { Try{HttpWebRequest HttpWebRequest= (HttpWebRequest) webrequest.create (url + (PostData = =""?"":"?") +postdata); Httpwebrequest.method="GET"; Httpwebrequest.contenttype="Text/html;charset=utf-8"; WebResponse WebResponse=HttpWebRequest.GetResponse (); HttpWebResponse HttpWebResponse=(HttpWebResponse) WebResponse; System.IO.Stream Stream=Httpwebresponse.getresponsestream (); System.IO.StreamReader StreamReader=NewSystem.IO.StreamReader (Stream, encoding.getencoding ("UTF-8")); Result= Streamreader.readtoend ();//the data returned by the requestStreamreader.close (); Stream. Close (); return true; } Catch(Exception ex) {result=Ex. Message; return false; } } /// <summary> ///Http POST Request/// </summary> /// <param name= "url" >Request Address</param> /// <param name= "PostData" >Request Parameters</param> /// <param name= "Result" >return Results</param> /// <returns></returns> Public Static BOOLWebhttppost (stringUrlstringPostData, out stringresult) { Try { byte[] ByteArray =System.Text.Encoding.UTF8.GetBytes (postdata); stringRequesturl = URL +PostData; HttpWebRequest HttpWebRequest= WebRequest.Create (Requesturl) asHttpWebRequest; Httpwebrequest.method="POST"; Httpwebrequest.contenttype="application/x-www-form-urlencoded"; Httpwebrequest.contentlength=bytearray.length; using(System.IO.Stream Stream =Httpwebrequest.getrequeststream ()) {stream. Write (ByteArray,0, bytearray.length); } HttpWebResponse HttpWebResponse= HttpWebRequest.GetResponse () asHttpWebResponse; using(System.IO.Stream Responsestream =Httpwebresponse.getresponsestream ()) {System.IO.StreamReader StreamReader=NewSystem.IO.StreamReader (Responsestream, Encoding.GetEncoding ("UTF-8")); Result= Streamreader.readtoend ();//the data returned by the requestStreamreader.close (); } return true; } Catch(Exception ex) {result=Ex. Message; return false; } }
-------------the WCF server Web. config configuration is as follows:----------------
<system.serviceModel> <services> <service name="Wcfservice.webuser"><!--How Web HTTP access is available in WCF--<endpoint binding="webhttpbinding"behaviorconfiguration="Webbehavior"contract="Wcfservice.iwebuser"/><!--provide WCF services, note that address= ' WCF ', in order to partition the address with the Web HTTP, add the reference after adding it automatically--<endpoint address="WCF"binding="BasicHttpBinding"contract="Wcfservice.iwebuser"/> </service> </services> <behaviors><!--How Web HTTP is available in WCF--<endpointBehaviors> <behavior name="Webbehavior"> <webhttp helpenabled="true"/> </behavior> </endpointBehaviors><!--How Web HTTP is available in WCF--<serviceBehaviors> <behavior><!--to avoid leaking metadata information, set the following values to false before deployment<servicemetadata httpgetenabled="true"Httpsgetenabled="true"/><!--to receive the fault exception details for debugging, set the following value to True. Set to false before deployment to avoid leaking exception information --<servicedebug includeexceptiondetailinfaults="false"/> </behavior> </serviceBehaviors> </behaviors> <protocolMapping> < Add binding="basichttpsbinding"Scheme="HTTPS"/> </protocolMapping> <servicehostingenvironment aspnetcompatibilityenabled="true"Multiplesitebindingsenabled="true"/> </system.serviceModel>
-------------WCF Service-------------
namespacewcfservice{//Note: Using the rename command on the Refactor menu, you can change the interface name "Iwebuser" in code and configuration files at the same time. [ServiceContract] Public InterfaceIwebuser {[OperationContract] [WebGet (Requestformat= Webmessageformat.json, Responseformat = Webmessageformat.json, bodystyle = webmessagebodystyle.bare, UriTemplate ="/showname?name={name}")] stringShowName (stringname); [OperationContract] [WebInvoke (Method="POST", Requestformat = Webmessageformat.json, Responseformat = Webmessageformat.json, bodystyle = WebMessageBodyStyle.Bare, UriTemplate ="/shownamebypost/{name}")] stringShownamebypost (stringname); }}
-----------the client traditional way and the Web HTTP method call----------------
Public Static voidMain (string[] args) {webuserclient WebUser=Newwebuserclient (); Console.WriteLine ("Please enter your name! "); stringWebName =Console.ReadLine (); stringWebresult =Webuser.showname (webname); Console.WriteLine (Webresult); Console.WriteLine ("Please enter your name! "); stringGetData =Console.ReadLine (); stringApigeturl ="Http://localhost:8423/WebUser.svc/ShowName"; stringJsongetmsg =string. Empty; BOOLStrgetresult = Webhttpget (Apigeturl,"name="+ GetData, outjsongetmsg); Console.WriteLine ("Request Result:"+ Strgetresult +"and returns the result:"+jsongetmsg); Console.WriteLine ("Please enter your name! "); stringPostData =Console.ReadLine (); stringApiposturl ="Http://localhost:8423/WebUser.svc/ShowNameByPost"; stringJsonpostmsg =string. Empty; BOOLStrpostresult = Webhttppost (Apiposturl,"/"+ PostData, outjsonpostmsg); Console.WriteLine ("Request Result:"+ Strpostresult +"and returns the result:"+jsonpostmsg); Console.ReadLine (); }
WCF Service support HTTP (get,post) mode Request Example