HttpWebRequest与HttpWebResponse进行数据采集时的注意点
? 一般的數(shù)據(jù)采集使用WebClient可以很方便的進(jìn)行,但是一些比較復(fù)雜(指需要較多的設(shè)置請求標(biāo)頭,以及重定向)的采集一般會使用HttpWebRequest或HttpWebResponse.
? 在需要給當(dāng)前請求附加Cookie時(shí),一般可以使用
?request.Headers.Add("Cookie", "ASPXSESSION=12345");
?或者 使用類似下面的語句
????????????? ?CookieCollection cookies = container.GetCookies(logUri);
??????????????? request.CookieContainer = new CookieContainer();
??????????????? foreach (Cookie cookie in cookies)
??????????????? {
??????????????????? cookie.Domain = dataUri.Host; //使用目標(biāo)數(shù)據(jù)頁的主機(jī)部分
??????????????????? request.CookieContainer.Add(cookie);
??????????????? }
?當(dāng)然多數(shù)情況下我們會使用前一種, 需要注意的是同時(shí)設(shè)置這兩個(gè)屬性時(shí),后一種?request.CookieContainer = new CookieContainer(); 會屏蔽掉前一種, 同時(shí)響應(yīng)流中的resposne.Cookies可用, 使用Headers.Add("xxxxx")方式時(shí),
你無法通過過response.Cookies 獲取返回的Cookie信息(Session標(biāo)志等), 不過兩種方式多可以通過resposne.Headers["Set-Cookie"]獲取返回的Cookie(session標(biāo)志等)
//注意當(dāng)value中包含如 "&","=","+"時(shí)需要使用,
//HttpUtility.UrlEncode( "+++xxx為什么不編碼也可以",Encoding.GetEncoding("GB2312"))?進(jìn)行編碼
//HttpUtility.UrlEncode(string) 默認(rèn)使用UTF-8進(jìn)行編碼
????????? byte[] data = Encoding.GetEncoding("GB2312").GetBytes("name1=value1&name2=value2&name3=value3");
??????????? HttpWebRequest request = HttpWebRequest.Create("http://www.xxx.com/Login.jsp") as HttpWebRequest;
??????????? request.AllowAutoRedirect = false;//禁止自動重定向
??????????? request.Method = "POST"; //使用post方法
??????????? request.ContentType = "application/x-www-form-urlencoded";//form提交時(shí)使用urlencode
??????????? request.ContentLength = data.Length;
??????????? //添加Cookie如果有必要
??????????? request.Headers.Add("Cookie", "ASPXSESSION=12345");
??????????? Stream uploadStream = request.GetRequestStream();
??????????? uploadStream.Write(data, 0, data.Length); //發(fā)送表單數(shù)據(jù)
??????????? uploadStream.Close();
??????????? HttpWebResponse resposne = request.GetResponse() as HttpWebResponse;
?????????? ?? StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));
????????? //獲取反回的頁面內(nèi)容
??????????? string html = sr.ReadToEnd();
??????????? resposne.Close();
?????????? //獲取Cookie(Session標(biāo)志等) Jsp一般為JSESSIONID=DA205A5E8FA2CE1CC39F3DA94076CF4F
??????????? string session = resposne.Headers["Set-Cookie"];
??????????? resposne.Close();
總結(jié)
以上是生活随笔為你收集整理的HttpWebRequest与HttpWebResponse进行数据采集时的注意点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《木偶之歌》
- 下一篇: ps快速将白底图片变为透明图片