WebRequest get web page garbled

Source: Internet
Author: User

Problem: In using WebRequest to get the source code is garbled.

Reason: 1, wrong encoding

WORKAROUND: Set the corresponding encoding

WebRequest request = WebRequest.Create (URL);
WebResponse response = await request. Getresponseasync ();

Stream stream = Response. GetResponseStream ();
StreamReader reader = new StreamReader (stream, encoding.getencoding (coding));//The coding here is the encoding of the page, you can use IE right-click to view the code.
Result = reader. ReadToEnd ();

Reader. Dispose ();
Reader. Dispose ();

2, the page is compressed

See if the HTML head,contentencoding is gzip-if yes, you need to unzip it. The following code is under WINRT.

WebRequest request = WebRequest.Create (URL);
WebResponse response = await request. Getresponseasync ();
Debug.WriteLine (((httpwebresponse) response). Statusdescription);
if (response. Headers.AllKeys.Contains ("content-encoding") && response. headers["Content-encoding"]. ToLower () = = "gzip")//Unzip first if using gzip
{
using (System.IO.Stream streamreceive = response. GetResponseStream ())
{
using (var ZipStream =
New System.IO.Compression.GZipStream (Streamreceive, System.IO.Compression.CompressionMode.Decompress))
{
using (StreamReader sr = new System.IO.StreamReader (ZipStream, encoding.getencoding (coding)))
{
Result = Sr. ReadToEnd ();
}
}
}
               }

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.