Use of HttpWebRequest

Source: Internet
Author: User
Tags getstream urlencode

The HttpWebRequest class takes advantage of the HTTP protocol and server interaction, usually through get and POST two ways to obtain and submit data. Here are a couple of ways to illustrate the following:

GET mode

The GET method completes the data submission by attaching parameters to the network address, for example, in address Http://www.studyofnet.com/?hl=zh-CN, the previous section http://www.studyofnet.com represents the URL of the data submission, and the latter part HL=ZH-CN represents an additional parameter, where HL represents a key (key) and ZH-CN represents the value of the key (value).

The program code is as follows:

C # codeCopy
  HttpWebRequest req = (HttpWebRequest) httpwebrequest.create ("Http://www.studyofnet.com?hl=zh-CN");
Req. Method = "GET";
using (WebResponse WR = req. GetResponse ())
{//To process the content of the received page here}

Use the GET method to submit Chinese data.

GET method to complete the data submission by attaching parameters in the network address, for Chinese encoding, there are two kinds of gb2312 and utf8 commonly used.

The program code that is accessed using the Gb2312 method is as follows:

C # codeCopy
Encoding myencoding = encoding.getencoding ("gb2312");
string address = "http://www.studyofnet.com/?" + httputility.urlencode ("parameter One", myencoding) + "=" + Httputility.urlencode ( "Value One", myencoding);
HttpWebRequest req = (HttpWebRequest) httpwebrequest.create (address);
Req. Method = "GET";
using (WebResponse WR = req. GetResponse ())
{//To process the content of the received page here}

In the above program code, we GET access to the URL http/ www.studyofnet.com , passed the parameter "parameter one = value One", because cannot tell the other party to submit the data encoding type, So the encoding method to the other side of the site as standard.

POST mode

The POST method completes the data submission by filling in the parameters in the page content, the format of the parameter is the same as the GET method, which is similar to the structure of hl=zh-cn&newwindow=1.

The program code is as follows:

C # codeCopy
string param = "hl=zh-cn&newwindow=1";
byte[] bs = Encoding.ASCII.GetBytes (param);
HttpWebRequest req = (HttpWebRequest) httpwebrequest.create ("http://www.studyofnet.com/");
Req. Method = "POST";
Req. ContentType = "application/x-www-form-urlencoded";
Req. ContentLength = BS. Length;
using (Stream Reqstream = req. GetRequestStream ())
{   reqstream.write (BS, 0, BS. Length);} using (WebResponse WR = req. GetResponse ()){   //where the content of the received page is processed}  

In the above code, we visited the URL of http://www.studyofnet.com, submitted the data in the form of GET and POST respectively, and received the content of the returned page. However, if the submitted parameter contains Chinese, then this processing is not enough, need to encode it, so that the other site can be recognized.

Submit Chinese data using POST

The POST method completes the data submission by filling in the parameter in the page content, because the submitted parameters can explain the encoding method used, so it is theoretically possible to achieve greater compatibility.

The program code that is accessed using the Gb2312 method is as follows:

C # codeCopy
Encoding myencoding = encoding.getencoding ("gb2312");
string param = Httputility.urlencode ("parameter One", myencoding) + "=" + Httputility.urlencode ("Value One", myencoding) + "&" + Httput Ility. UrlEncode ("parameter Two", myencoding) + "=" + Httputility.urlencode ("Value two", myencoding);
byte[] postbytes = Encoding.ASCII.GetBytes (param);
HttpWebRequest req = (HttpWebRequest) httpwebrequest.create ("http://www.studyofnet.com/");
Req. Method = "POST";
Req. ContentType = "application/x-www-form-urlencoded;charset=gb2312";
Req. ContentLength = Postbytes.length;
using (Stream Reqstream = req. GetRequestStream ())
{   reqstream.write (BS, 0, BS. Length);} using (WebResponse WR = req. GetResponse ()){   

From the above code can be seen, the POST Chinese data, the first time using the UrlEncode method to convert the medium character to the encoded ASCII code, and then submitted to the server, the submission can be described in the way of encoding, to enable the other server to correctly parse.

How to use the HttpWebRequest class in the C # language

C # codeCopy
Using System;
Using System.Collections.Generic;
Using System.IO;
Using System.Net;
Using System.Text;
Namespace HttpWeb
{<summary>//HTTP operation class///</summary> public static class Httptest{<summary>///Get URL HTML//</summary>//<param name= "url" > URL &LT;/PARAM&G         T <returns> </returns> public static string gethtml (String URL){WebRequest wrt;            WRT = WebRequest.Create (URL); Wrt.            Credentials = CredentialCache.DefaultCredentials;            WebResponse WRP; WRP = wrt.            GetResponse (); String reader = new StreamReader (WRP. GetResponseStream (), encoding.getencoding ("gb2312")).            ReadToEnd (); Try{wrt. GetResponse (). Close (); } catch (WebException ex){Throw ex;} return reader; }<summary>///Get website Cookies//</summary>//<param name= "url" > URL </param>///<param name= " Cookie ">cookie </param>///<returns> </returns> public static string gethtml (String URL, out string Cookies){WebRequest wrt; wrt = WebRequest.Create (URL); wrt. Credentials = CredentialCache.DefaultCredentials; WebResponse WRP; WRP = wrt. GetResponse (); String html = new StreamReader (WRP. GetResponseStream (), encoding.getencoding ("gb2312")). ReadToEnd (); Try{wrt. GetResponse (). Close (); } catch (WebException ex){Throw ex;} Cookie = WRP. Headers.get ("Set-cookie"); return HTML; public static string gethtml (String URL, string postdata, String cookie, out string header, String server){return gethtml (server, URL, PostData, Cookie, out header);} public static string gethtml (String server, String URL, string postdata, String cookie, out string header){byte[] byterequest = encoding.getencoding ("gb2312"). GetBytes (PostData); return gethtml (server, URL, Byterequest, Cookie, out header); public static string gethtml (String server, String URL, byte[] byterequest, String cookie, out string header){byte[] bytes = gethtmlbybytes (server, URL, Byterequest, Cookie, out header); Stream GetStream = new MemoryStream (bytes); StreamReader StreamReader = new StreamReader (GetStream, encoding.getencoding ("gb2312")); String getString = Streamreader.readtoend (); Streamreader.close (); Getstream.close (); return getString; }<summary>////Post mode browse///</summary>/<param name= "Server" > Server address </param>//<param NA Me= "url" > URL </param>//<param name= "Byterequest" > Stream </param>//<param name= "cookies" > Cookies </param>//<param name= "header" > Handle </param>//<returns> </returns> Public Static byte[] Gethtmlbybytes (string server, String URL, byte[] byterequest, String cookie, out string header){Long contentlength; HttpWebRequest HttpWebRequest; HttpWebResponse WebResponse; Stream GetStream; HttpWebRequest = (HttpWebRequest) httpwebrequest.create (URL); Cookiecontainer CO = new Cookiecontainer (); Co. Setcookies (new Uri (server), cookie); Httpwebrequest.cookiecontainer = CO; Httpwebrequest.contenttype = "application/x-www-form-urlencoded"; Httpwebrequest.accept = "Image/gif, Image/x-xbitmap, Image/jpeg, Image/pjpeg, Application/x-shockwave-flash, Application/vnd.ms-excel, Application/vnd.ms-powerpoint, Application/msword, */* "; Httpwebrequest.referer = server; Httpwebrequest.useragent = "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon;. NET CLR 1.1.4322) "; Httpwebrequest.method = "Post"; Httpwebrequest.contentlength = Byterequest.length; Stream stream; stream = Httpwebrequest.getrequeststream (); Stream. Write (byterequest, 0, byterequest.length); Stream. Close (); WebResponse = (HttpWebResponse) httpwebrequest.getresponse (); Header = WebResponse.Headers.ToString (); GetStream = WebResponse.GetResponseStream (); ContentLength = Webresponse.contentlength; byte[] outbytes = new Byte[contentlength]; Outbytes = readfully (GetStream); Getstream.close (); return outbytes; } public static byte[] Readfully (Stream stream){byte[] buffer = new byte[128], using (MemoryStream ms = new MemoryStream ()){while (true){int read = stream. Read (buffer, 0, buffer. Length); if (read <= 0) return Ms. ToArray (); Ms. Write (buffer, 0, read); } } }<summary>///Get Mode///</summary>//<param name= "url" > URL </param>///<param name= "Cooki E ">cookies </param>//<param name=" header "> Handle </param>//<param name=" Server "> Server </ param>//<param name= "val" > Server </param>//<returns> </returns> public static string gethtm L (string URL, String cookie, out string header, String server){return gethtml (URL, cookie, out header, server, "");}<summary>///Get mode Browse///</summary>//<param name= "url" >get URL </param>//<param name= " Cookie ">cookie </param>//<param name=" header > Handle </param>//<param name= "Server" > Server address </param>//<param name= "val" > </param>//<returns> </returns> public static string Geth Tml (string URL, String cookie, out string header, String server, String val){HttpWebRequest HttpWebRequest; HttpWebResponse WebResponse; Stream GetStream; StreamReader StreamReader; String getString = ""; HttpWebRequest = (HttpWebRequest) httpwebrequest.create (URL); httpwebrequest.accept = "*/*"; Httpwebrequest.referer = server; Cookiecontainer CO = new Cookiecontainer (); Co. Setcookies (new Uri (server), cookie); Httpwebrequest.cookiecontainer = CO; Httpwebrequest.useragent = "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon;. NET CLR 1.1.4322) "; Httpwebrequest.method = "GET"; WebResponse = (HttpWebResponse) httpwebrequest.getresponse (); Header = WebResponse.Headers.ToString (); GetStream = WebResponse.GetResponseStream (); StreamReader = new StreamReader (GetStream, encoding.getencoding ("gb2312")); getString = Streamreader.readtoend (); Streamreader.close (); Getstream.close (); return getString; } }}

Use of HttpWebRequest

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.