using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
GetHtmlPage("http://www.baidu.com/", Encoding.GetEncoding("gb2312"));
Console.Read();
}
public static string GetHtmlPage(string URL, Encoding encodingFormat)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
CookieContainer cc = new CookieContainer();
StreamReader sr = null;
string strCookies = string.Empty;
try
{
request = (HttpWebRequest)WebRequest.Create(URL);//实例化web访问类
request.ContentType = "application/x-www-form-urlencoded";//模拟头
request.AllowAutoRedirect = false;
request.CookieContainer = cc;
request.KeepAlive = true;
request.Method = "GET";
request.KeepAlive = true;
request.Headers.Add("Cookie:" + strCookies);
response = (HttpWebResponse)request.GetResponse();
//设置cookie
strCookies = request.CookieContainer.GetCookieHeader(request.RequestUri);
//取再次跳转链接
sr = new StreamReader(response.GetResponseStream(), encodingFormat);
string content = sr.ReadToEnd();
return content;
}
catch (Exception)
{
//第一次GET出错
}
finally
{
if (request != null)
{
request.Abort();
}
if (response != null)
{
response.Close();
}
if (sr != null)
{
sr.Close();
}
}
return "";
}
}
}
GET方法获得html页面内容
最新推荐文章于 2024-06-20 10:30:27 发布