C # obtain webpage content

Source: Internet
Author: User

Susing System. Net;
Using System. IO;
Using System. Text;


// Method 1:
// Create a request for the URL.

WebRequest request = WebRequest. Create ("http://www.hao123.com /");
// If required by the server, set the credentials.
Request. Credentials = CredentialCache. DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse) request. GetResponse ();
// Display the status.
Response. Write (response. StatusDescription );
// Get the stream containing content returned by the server.
Stream dataStream = response. GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream, Encoding. Default); // Note: Convert Chinese characters to UTF8 format
// Read the content.
String responseFromServer = reader. ReadToEnd ();
// Display the content.
Response. Write (responseFromServer );
// Cleanup the streams and the response.
Reader. Close ();
DataStream. Close ();
Response. Close ();

// Method 2:
WebClient client = new WebClient ();

// Add a user agent header in case
// Requested URI contains a query.

Client. Headers. Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;. net clr 1.0.3705 ;)");

Stream data = client. OpenRead ("http://www.hao123.com /");
StreamReader reader = new StreamReader (data, Encoding. Default); // Note: Convert Chinese characters to UTF8 format
String s = reader. ReadToEnd ();
Response. Write (s );
Data. Close ();
Reader. Close ();

// Method 3:
WebClient client = new WebClient ();
// Client. DownloadFile ("http://www.hao123.com 41522,20.22123.htm /");
String reply = client. DownloadString ("http://www.hao123.com /");
Response. Write (reply );

Related Article

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.