最近在网上发现一些有意思的东西,想抓下来,被一个小问题给卡住了,程序如何发送post请求都没法得到想要的结果,利用火狐仔细研究下发现需要打开一次页面,再提交参数就ok,这就好办了
学过网页编程的都知道,session保持会话状态,使得类似登陆功能可以连续保持。
但用程序发送post请求的时候,session就会丢失。
究其原因,还是要看session的原理。
其实session一般都有个sessionID保存在cookie里。
每次请求数据都会发送上次的cookie到服务器。
PHP的一般为 PHPSESSIONID
asp.NET的好像是ASPNETSESSIONID
.....
其实只要把请求返回的sesionID给保存下来。再赋值给下次要请求的request对象就OK了,只要此次session在服务端没过期。
如下代码实现:
private static CookieContainer m_Cookie = new CookieContainer(); private static string post(string postURL, string postData, Encoding pageEncoding) { HttpWebRequest httpWebRequest; HttpWebResponse httpWebResponse; byte[] bytesToPost = pageEncoding.GetBytes(postData); try { httpWebRequest = WebRequest.Create(postURL) as HttpWebRequest; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = true; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.CookieContainer = m_Cookie;//设置上一个访问页面的cookie 保持session httpWebRequest.ContentLength = bytesToPost.Length; Stream requestStream = httpWebRequest.GetRequestStream(); requestStream.Write(bytesToPost, 0, bytesToPost.Length);//写入post信息 requestStream.Close(); httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; m_Cookie = httpWebRequest.CookieContainer;//访问后更新cookie Stream responseStream = httpWebResponse.GetResponseStream(); string resData; using (StreamReader resSR = new StreamReader(responseStream, pageEncoding)) { resData = resSR.ReadToEnd(); resSR.Close(); responseStream.Close(); } return resData; } catch (Exception err) { throw err; }