HttpWebRequest与HttpWebResponse进行数据采集时的注意点


  一般的数据采集使用WebClient可以很方便的进行,但是一些比较复杂(指需要较多的设置请求标头,以及重定向)的采集一般会使用HttpWebRequest或HttpWebResponse.

  在需要给当前请求附加Cookie时,一般可以使用
 request.Headers.Add("Cookie", "ASPXSESSION=12345");
 或者 使用类似下面的语句
               CookieCollection cookies = container.GetCookies(logUri);
                request.CookieContainer = new CookieContainer();
                foreach (Cookie cookie in cookies)
                {
                    cookie.Domain = dataUri.Host; //使用目标数据页的主机部分
                    request.CookieContainer.Add(cookie);
                }
 当然多数情况下我们会使用前一种, 需要注意的是同时设置这两个属性时,后一种 request.CookieContainer = new CookieContainer(); 会屏蔽掉前一种, 同时响应流中的resposne.Cookies可用, 使用Headers.Add("xxxxx")方式时,
你无法通过过response.Cookies 获取返回的Cookie信息(Session标志等), 不过两种方式多可以通过resposne.Headers["Set-Cookie"]获取返回的Cookie(session标志等)

使用 HttpWebRequest与HttpWebResponse获取Session标志
//注意当value中包含如 "&","=","+"时需要使用,
//HttpUtility.UrlEncode( "+++xxx为什么不编码也可以",Encoding.GetEncoding("GB2312")) 进行编码
//HttpUtility.UrlEncode(string) 默认使用UTF-8进行编码
          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提交时使用urlencode
            request.ContentLength = data.Length;
            //添加Cookie如果有必要
            request.Headers.Add("Cookie", "ASPXSESSION=12345");
            Stream uploadStream = request.GetRequestStream();
            uploadStream.Write(data, 0, data.Length); //发送表单数据
            uploadStream.Close();
            HttpWebResponse resposne = request.GetResponse() as HttpWebResponse;
              StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));
          //获取反回的页面内容
            string html = sr.ReadToEnd();

            resposne.Close();
           //获取Cookie(Session标志等) Jsp一般为JSESSIONID=DA205A5E8FA2CE1CC39F3DA94076CF4F
            string session = resposne.Headers["Set-Cookie"];
            resposne.Close();
原文地址:https://www.cnblogs.com/wdfrog/p/1393679.html