虽然站长的httphelper 类已经很完美.但是我觉得不好的地方就是cookies处理问题.. 之前因为这个问题导致BUG让我搞了一个星期
我的类有以下特点..只需要创建一次..然后get post 都实现cookies的同步
而且每次请求都会带上上次同步好的cookies
注意: 不是简单的同步
一些网址不返回cookies 或是单纯的改变某key的值..这时 你不可能完全覆盖 上次请求返回的cookies 这时我的类就派上用场了
不废话了上代码
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Class_tools
{
/// <summary>
/// 支持Cookies共享的 http类 该类请求.所有的Cookies 都会同步更新的
/// </summary>
public class Tu_MyHttp
{
/// <summary>
/// 共享的cookies
/// </summary>
public string Cookies { set; get; }
/// <summary>
/// 浏览器标识
/// </summary>
public string UserAgent { set; get; }
public string SeedGet(string url)
{
HttpItem item = new HttpItem();
item.URL = url;
return SeedHttpItem(item).Html;
}
public string SeedPost(string url, string postData)
{
HttpItem item = new HttpItem();
item.URL = url;
item.Method = "POST";
item.Postdata = postData;
return SeedHttpItem(item).Html;
}
public HttpResult SeedHttpItem(HttpItem item)
{
item.Cookie = Cookies;
if (!string.IsNullOrWhiteSpace(UserAgent))
{
item.UserAgent = UserAgent;
}
HttpResult result = Tu_web.GetResult(item);
string cookies = Cookies;
Tu_web.UpdateCookies(result, ref cookies);
if (!string.IsNullOrWhiteSpace(cookies))
{
Cookies = cookies;
}
return result;
}
}
}
核心方法 更新cookies方法,cookies 这些都会自动简化 因为本人封闭的类也调用了其他很多字符串处理小方法..所以这些请按个人理解自己做
[C#] 纯文本查看 复制代码 public static void UpdateCookies(HttpResult itemT,ref string cookies)
{
if (string.IsNullOrWhiteSpace(itemT.Cookie))
{
return;
}
if (string.IsNullOrWhiteSpace(itemT.Cookie))
{
return;
}
Dictionary<string, string> DicCookies = new Dictionary<string, string>();
////临时测试
//cookies = itemT.Cookie;
//return;
itemT.Cookie = cookies + ";" + itemT.Cookie;
string[] rows = itemT.Cookie.Split(';');
foreach (var item in rows)
{
if (!string.IsNullOrWhiteSpace(item))
{
string newrow = item;
//newrow = newrow.Replace("httponly,", "").Trim();
string name = "";
string value = "";
if (newrow.Contains("="))
{
name = Tu_string.GetLeft(newrow, "=").Trim();
value = Tu_string.GetRight(newrow, "=").Trim();
}
if (name == "")
{
name = newrow;
}
if (name.Contains(","))
{
string temp = name;
name = Tu_string.GetRight(name, ",",true);
if (string.IsNullOrWhiteSpace(name))
{
name = temp;
}
}
if (!string.IsNullOrWhiteSpace(name) && name != "expires" && value != "deleted" && !name.Contains("/"))
{
if (DicCookies.ContainsKey(name))
{
DicCookies[name] = value;
}
else
{
DicCookies.Add(name, value);
}
}
}
}
string newCookies = "";
foreach (var item in DicCookies)
{
newCookies += item.Key + "=" + item.Value + "; ";
}
cookies = newCookies.Trim().TrimEnd(';');
itemT.Cookie = cookies;
}
|