(1) Get
Send URL Request
Set Request mode
Format Request Content
Get response object, receive stream
Read stream
Private stringGet (stringURL) { stringall =string. Empty; //Send RequestHttpWebRequest request =WebRequest.Create(URL) asHttpWebRequest; Request. Method="Get";//Setup MethodRequest. ContentType ="Text/html;charset=utf-8"; //Get a responseHttpWebResponse response =(HttpWebResponse) Request. GetResponse (); //Read StreamStream stream =Response. GetResponseStream (); StreamReader SR=NewStreamReader (stream, Encoding.UTF8); All=Sr. ReadToEnd (); //Close the streamStream. Close (); Sr. Close (); returnAll ; }
(2) Post
Send URL Request
Set Request mode
Format Request Content
Set the request content length (can not be set) (length is the length of the byte array, not the length of the string type)
Add post data to the request stream (heavy GetRequestStream ())
Receive response object, receive stream
Read stream
Public Static stringPost (stringPostData,stringURL) {HttpWebResponse hw; stringresult =string. Empty; HttpWebRequest req=(HttpWebRequest) webrequest.create (URL); Req. Method="POST"; Req. ContentType="Application/json"; #regionAdd Post Parametersbyte[] data =Encoding.UTF8.GetBytes (postdata); req. ContentLength = data. Length; using(Stream Reqstream = req. GetRequestStream ()) { reqstream.write (data, 0 , data. LENGTH);//Put the Post object into the request stream reqstream.close (); } #endregion Try{HttpWebResponse resp=(HttpWebResponse) req. GetResponse (); Stream Stream=resp. GetResponseStream (); //Get Response Content using(StreamReader reader =NewStreamReader (Stream, Encoding.UTF8)) {Result=Reader. ReadToEnd (); } } Catch(WebException W) {HW=(HttpWebResponse) w.response; StreamReader SR=NewStreamReader (HW. GetResponseStream (), Encoding.UTF8,false); Result=Sr. ReadToEnd (); } returnresult; }
C#get, Post