C# 使用代理访问网页

其他的就不多说了,上代码,作为收藏用。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.905010.com");
request.Method = "GET";
request.Timeout = 10000;
request.KeepAlive = false;
request.Proxy = gProxy;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;

这里要解释下为什么要用

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

有时候返回的内容全是乱码,原因就是压缩不是GZIP而是Deflate。

VB.NET是这样写

request.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate

Read More

发表评论

邮箱地址不会被公开。 必填项已用*标注