A detailed description of HttpWebRequest usage in C #

Source: Internet
Author: User
Tags getstream urlencode

This example describes the use of HttpWebRequest in C #. Share to everyone for your reference. Specific as follows:

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 appending parameters to the network address, for example, in address Http://www.jb51.net/?hl=zh-CN, the previous section http://www.jb51.net 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:


The code is as follows:

HttpWebRequest req = (HttpWebRequest) httpwebrequest.create ("Http://www.jb51.net?hl=zh-CN");

Req. Method = "GET";

using (WebResponse WR = req. GetResponse ())

{

Handle 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:


The code is as follows:

Encoding myencoding = encoding.getencoding ("gb2312");

string address = "http://www.jb51.net/?" + httputility.urlencode ("parameter One", myencoding) + "=" + Httputility.urlencode ("value One", M yencoding);

HttpWebRequest req = (HttpWebRequest) httpwebrequest.create (address);

Req. Method = "GET";

using (WebResponse WR = req. GetResponse ())

{

Handle the content of the received page here

}

In the above program code, we get access to the URL http://www.jb51.net, passed the parameter "parameter one = value One", because unable to tell the other party to submit 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:


The code is as follows:

string param = "Hl=zh-cn&newwindow;=1";

byte[] bs = Encoding.ASCII.GetBytes (param);

HttpWebRequest req = (HttpWebRequest) httpwebrequest.create ("http://www.jb51.net/");

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 ())

{

Handle the content of the received page here

}

In the above code, we visited the URL of http://www.jb51.net, 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:


The code is as follows:

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.jb51.net/");

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 ())

{

Handle the content of the received page here

}

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


The code is as follows:

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 </param>

<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 Site Cookies

</summary>

<param name= "url" > URL </param>

<param name= "Cookie" >cookie </param>

<returns> </returns>

public static string gethtml (String URL, out string cookie)

{

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 browsing

</summary>

<param name= "Server" > Server address </param>

<param name= "url" > URL </param>

<param name= "Byterequest" > Flow </param>

<param name= "Cookie" >cookie </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= "Cookie" >cookies </param>

<param name= "header" > Handle </param>

<param name= "Server" > Servers </param>

<param name= "val" > Server </param>

<returns> </returns>

public static string gethtml (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 gethtml (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;

}

}

}

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
A detailed description of HttpWebRequest usage in C #

This address: http://www.paobuke.com/develop/c-develop/pbk23338.html






Related content C # methods for implementing file compression and decompression example "Zip format" WinForm form method of passing values (example) C # simple way to write XML files C # make Jigsaw puzzles with control drag technology
C # implements methods for writing logs to a text file C # to create, read, and modify Excel. Netà????? Ê?? ÷ (GC)?-àí?3?? C # timed off form instances

A detailed description of HttpWebRequest usage in C #

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.