First, Get mode transmission
//URL is the requested URL, the param parameter is the condition that needs to be queried (parameters received by the server, not NULL)//returns the response of the request Public stringHttpGet (stringURL, dictionary<string, string>param) { if(param! =NULL)//in case of parameters, the stitching URL{URL= URL +"?"; foreach(varIteminchparam) {URL= URL + item. Key +"="+ Item. Value +"&"; } URL= URL. Substring (0Url. Length-1); } HttpWebRequest Request= WebRequest.Create (URL) asHttpWebRequest;//Create requestRequest. Method ="GET";//Request method is getHttpWebResponse Res;//defines the returned response Try{res= (HttpWebResponse) request. GetResponse ();//request is sent here and a response is received } Catch(WebException ex) {res=(HttpWebResponse) ex. Response; } StreamReader SR=NewStreamReader (Res. GetResponseStream (), Encoding.UTF8); stringContent = Sr. ReadToEnd ();//response converted to string string returncontent; }
Second, POST mode transmission
Public Static stringHttpPost (stringURL, dictionary<string, string>param) {HttpWebRequest Request= WebRequest.Create (URL) asHttpWebRequest;//Create requestCookiecontainer Cookiecontainer =NewCookiecontainer (); Request. Cookiecontainer=Cookiecontainer; Request. AllowAutoRedirect=true; //request. Allowreadstreambuffering = true;Request. maximumResponseHeadersLength =1024x768; Request. Method="POST";//Request mode is postRequest. AllowAutoRedirect =true; Request. maximumResponseHeadersLength=1024x768; Request. ContentType="Application/json"; Jobject JSON=NewJobject (); if(Param. Count! =0)//adding parameters to a JSON object { foreach(varIteminchparam) {JSON. ADD (item. Key, item. Value); } } stringjsonstring = json. ToString ();//JSON string to get parameters byte[] Jsonbyte =Encoding.UTF8.GetBytes (jsonstring); Stream Poststream=request. GetRequestStream (); Poststream.write (Jsonbyte,0, Jsonbyte. Length); Poststream.close (); //send request and get corresponding response dataHttpWebResponse Res; Try{res=(HttpWebResponse) request. GetResponse (); } Catch(WebException ex) {res=(HttpWebResponse) ex. Response; } StreamReader SR=NewStreamReader (Res. GetResponseStream (), Encoding.UTF8); stringContent = Sr. ReadToEnd ();//Get response string returncontent; }
The put and delete methods are basically similar to the above. There's no more explanation here.
C # Background get, POST, PUT, delete transport send JSON data