|
楼主 |
发表于 2014-4-24 09:34:37
|
显示全部楼层
如何储存cookie呢,我使用的httphelp类比较奇怪,用这个类不知道如何独立保存cookie
public class HttpHelper1
{
//获取代理ip
public static string GetIp()
{
WebClient myc = new WebClient();
Byte[] data = myc.DownloadData("http://i.ixiake.com/?ip=getip");
string html = Encoding.Default.GetString(data);
return html;
}
/// <summary>
/// 循环CookieCollection,把里面的cookie值放进CookieContainer容器中
/// </summary>
/// <param name="mycookie">CookieContainer容器</param>
/// <param name="newcookie">CookieCollection</param>
public static void UpdateCookie(ref CookieContainer mycookie, CookieCollection newcookie)
{
if (newcookie.Count > 0)
{
foreach (Cookie coo in newcookie)
{
mycookie.Add(coo);
}
}
}
/// <summary>
/// POST提交数据
/// </summary>
/// <param name="Url">post地址</param>
/// <param name="postDataStr">要提交的数据</param>
/// <param name="refrere">来路</param>
/// <param name="isutf8">是否是utf8</param>
/// <param name="sendmode">普通提交还是内容提交,例如文章提交要设为True</param>
/// <param name="cookie">CookieContainer,cookie容器</param>
/// <param name="timeout">超时时间,秒为单位</param>
/// <param name="useragent">客户端信息</param>
/// <param name="isPostOnGzip">是否启用Gzip压缩</param>
/// <returns>返回提交后数据</returns>
public static string HttpPOST(string Url, string proxystr, string postDataStr, string refrere, bool isutf8, bool sendmode, ref CookieContainer cookie, int timeout, string useragent, bool isPostOnGzip)
{
string cstr = "提交前Cookie:" + cookie.GetCookieHeader(new Uri(Url)); //定义字符串保存提交前后的cookie数据,用于分析
Stream myResponseStream = null; //定义服务器返回流
HttpWebResponse response = null; //定义服务器返回的请求
HttpWebRequest request = null;//定义提交请求
try
{
WebProxy proxy = new WebProxy();
System.Net.ServicePointManager.Expect100Continue = false;//当要POST的数据大于1024字节的时候,是否分成两步
System.Net.ServicePointManager.DefaultConnectionLimit = 1000;//设置最大并发连接,避免同时多个提交时出现失败
request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(Url));//根据当前url初始化请求
request.ServicePoint.Expect100Continue = false;////当要POST的数据大于1024字节的时候,是否分成两步
if (proxystr.Length > 0)
{
proxy = new WebProxy(proxystr);
request.Proxy = proxy;
}
request.CookieContainer = cookie;//设置cookie容器
request.Method = "POST";//设置提交方式
if (isPostOnGzip)
request.AutomaticDecompression = DecompressionMethods.GZip;
if (sendmode)//如果是内容提交,则加上此格式,这个是必须的,否则类似文章发布这样的提交无法被服务器识别
{
string split = postDataStr.Substring(postDataStr.IndexOf("-----------------------------") + 29);
split = split.Remove(split.IndexOf("\n"));
request.ContentType = "multipart/form-data; boundary=---------------------------" + split;
}
else
{
request.ContentType = "application/x-www-form-urlencoded";//普通提交例如登录这样的,加上此格式
}
request.Referer = refrere;//设置来路
request.Timeout = timeout * 1000;//设置超时时间,毫秒
request.AllowAutoRedirect = false;//是否跟随重定向
request.Accept = "*/*";//设置标头
request.Headers.Add("Accept-Language", "zh-CN");//设置标头
request.Headers.Add("Cache-Control", "no-cache");//设置标头
request.UserAgent = useragent;//设置标头,客户端信息
byte[] requestBytes = isutf8 ? System.Text.Encoding.UTF8.GetBytes(postDataStr) : System.Text.Encoding.Default.GetBytes(postDataStr);//根据指定的编码将要提交的数据变成字节数组
request.ContentLength = requestBytes.Length;//设置请求的长度
string header = request.Headers.ToString();//设置请求的头
Stream myRequestStream = request.GetRequestStream();//获取提交流
using (Stream writer = myRequestStream)
{
writer.Write(requestBytes, 0, requestBytes.Length);//提交数据到服务器
}
response = (HttpWebResponse)request.GetResponse();//获取服务器返回
myResponseStream = response.GetResponseStream();//获取服务器返回流
if (response.ContentEncoding.ToLower().Contains("gzip"))//如果是gzip,则用gzip的方式解压流
{
myResponseStream = new GZipStream(myResponseStream, CompressionMode.Decompress);
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
myResponseStream = new DeflateStream(myResponseStream, CompressionMode.Decompress);
}
string retString = isutf8 ? (new StreamReader(myResponseStream, Encoding.UTF8)).ReadToEnd() : (new StreamReader(myResponseStream, Encoding.Default)).ReadToEnd();//根据指定的编码将服务器返回流转换成字符串
cstr += "\r\n提交后Cookie:" + cookie.GetCookieHeader(new Uri(Url));//拼接提交后cookie,用于分析
retString = retString + "\r\n\r\n=================================================\r\n\r\n本次请求:" + Url + " 响应结果:" + response.StatusCode + "\r\n\r\n" + cstr + "\r\n" + request.CookieContainer.GetCookieHeader(new Uri(Url)) + "\r\nrequest:\r\n" + header + "\r\nresponse:\r\n" + response.Headers.ToString() + "\r\n\r\n=================================================\r\n\r\n";
UpdateCookie(ref cookie, response.Cookies);//将post成功以后得到的新cookie放入cookie容器里面
return retString;
}
catch (Exception ex)
{
return ex.Message;//如果报错,返回错误信息
}
finally
{//最后关闭各种流,各种请求,这里不管报不报错都会最终执行
if (myResponseStream != null)
myResponseStream.Close();
if (response != null)
response.Close();
if (request != null)
request.Abort();
}
}
|
|