您的位置:首页 > 理论基础 > 计算机网络

用httpwebrequest访问跨域网站时对CookieContainer的处理

2010-09-23 10:25 561 查看
前几天,想对一个网站实现自动登陆后提交相关数据,没有想到一直登陆不成功(验证码输入正确),后来用我的 WebClient 制作调试Http的post 和 get 工具 调试又可以的,郁闷!

第二天早上起来,突然想到可能是跨域的问题,之前有见过说CookieContainer在提交时,只发送当前域的cookie,其它的不提交,在网上搜索了一番,果然找到了 见 http://blog.csdn.net/ETstudio/archive/2007/11/21/1897071.aspx,我也把相关Dll Reflector 了一遍,果然找到了

namespace System.Net
{
using System;

internal static class CookieModule
{
internal static void OnReceivedHeaders(HttpWebRequest httpWebRequest)
{
try
{
if (httpWebRequest.CookieContainer != null)
{
HttpWebResponse response = httpWebRequest._HttpResponse;
if (response != null)
{
CookieCollection cookies = null;
try
{
string setCookie = response.Headers.SetCookie;
if ((setCookie != null) && (setCookie.Length > 0))
{
cookies = httpWebRequest.CookieContainer.CookieCutter(response.ResponseUri, "Set-Cookie", setCookie, false);
}
}
catch
{
}
try
{
string setCookieHeader = response.Headers.SetCookie2;
if ((setCookieHeader != null) && (setCookieHeader.Length > 0))
{
CookieCollection cookies2 = httpWebRequest.CookieContainer.CookieCutter(response.ResponseUri, "Set-Cookie2", setCookieHeader, false);
if ((cookies != null) && (cookies.Count != 0))
{
cookies.Add(cookies2);
}
else
{
cookies = cookies2;
}
}
}
catch
{
}
if (cookies != null)
{
response.Cookies = cookies;
}
}
}
}
catch
{
}
}

internal static void OnSendingHeaders(HttpWebRequest httpWebRequest)
{
try
{
if (httpWebRequest.CookieContainer != null)
{
string str;
httpWebRequest.Headers.RemoveInternal("Cookie");
string cookieHeader = httpWebRequest.CookieContainer.GetCookieHeader(httpWebRequest.Address, out str);
if (cookieHeader.Length > 0)
{
httpWebRequest.Headers["Cookie"] = cookieHeader;
}
}
}
catch
{
}
}
}
}


由此可见,问题也就找到了,于是自己写了一个方法来处理cookie,不过,也要注意,接收的时候,cookie的存放是有区别的!!!

另外,顺便贴一下,页面前台是如何解决跨域问题的

见疯狂的跨域技术:http://itgeeker.com/mathml/readpaper?pid=53
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: