看代码
get方法
/// <summary>
/// 传入URL返回网页的html代码带有证书的方法
/// </summary>
public string GetUrltoHtml(string Url)
{
StringBuilder content = new StringBuilder();
try
{
// 与指定URL创建HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)";
request.Method = "GET";
request.Accept = "*/*";
//如果方法验证网页来源就加上这一句如果不验证那就可以不写了
request.Referer = "http://www.easck.com//txw1958.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://www.easck.com//txw1958.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));
request.CookieContainer = objcok;
//不保持连接
request.KeepAlive = true;
// 获取对应HTTP请求的响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 获取响应流
Stream responseStream = response.GetResponseStream();
// 对接响应流(以"GBK"字符集)
StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"));
// 开始读取数据
Char[] sReaderBuffer = new Char[256];
int count = sReader.Read(sReaderBuffer, 0, 256);
while (count > 0)
{
String tempStr = new String(sReaderBuffer, 0, count);
content.Append(tempStr);
count = sReader.Read(sReaderBuffer, 0, 256);
}
// 读取结束
sReader.Close();
}
catch (Exception)
{
content = new StringBuilder("Runtime Error");
}
return content.ToString();
}
post方法。
///<summary>
///采用https协议访问网络
///</summary>
public string OpenReadWithHttps(string URL, string strPostdata)
{
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "post";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/x-www-form-urlencoded";
CookieContainer objcok = new CookieContainer();
objcok.Add(new Uri("http://www.easck.com//txw1958.cnblogs.com"), new Cookie("键", "值"));
objcok.Add(new Uri("http://www.easck.com/pre>
特点:
1.还算有点水类型的,练习成功后可以小牛一把。
2.适应于需要登录才能访问的页面。
3.获取的数据类型为HTML文档。
4.请求方法为Get/Post
总结一下,其它基本的技能就这几个部分,如果再深入的话那就是基本技能的组合了
比如,
1. 先用Get或者Post方法登录然后取得Cookie再去访问页面得到信息,这种其它也是上面技能的组合,这里需要以请求后做这样一步。response.Cookie
这就是在你请求后可以得到当次Cookie的方法,直接取得返回给上一个方法使用就行了,上面我们都是自己构造的,在这里直接使用这个Cookie就可以了。










