CURL处理跨域Cookies
Category : 软件技术
CURL处理跨域的Cookies
CURL是一款功能强大的开源HTTP协议库,可以模拟各种类型的HTTP/HTTPS报文。闻道软件工作室的多款系统软件中都使用到了CURL。
在使用CURL提交HTTP请求模拟登陆时,需要记录下连接的COOKIES,以维护登陆的状态。在大部分HTTP的模拟登陆中,设置以下两个参数即可在一条连接中保留状态。
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, GetCookiesFile().c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, GetCookiesFile().c_str());
分别表示不是将后续的请求中的Cookies保留到文件以及将文件中的cookies添加到当前的请求。
但是在一些网站中可能会用到一些子域名的URL,因为读取COOKIES是按照域名读取,虽然是子域名,但是仍然读取不了。这就是跨域cookies的问题。
为了解决这个问题只能从返回的header中读取set-cookies字段并分析自己保存。这样也有一个好处,COOKIES可以直接保存在内存里,没有磁盘IO操作。
在设置数据返回回调函数时要设置这个参数
curl_easy_setopt(curl, CURLOPT_HEADERDATA, this);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, HttpGet::CallBack);
表示处理header数据。
获取cookies内容接口如下:
void HttpGet::GetCookiesContent(string strContent)
{
int iStart = 0;
int iEnd = 0;
string strTmp = strContent;
iStart = strContent.find(“Set-Cookie:”) + strlen(“Set-Cookie:”);
while(iStart >= strlen(“Set-Cookie:”))
{
strTmp = strTmp.substr(iStart,strTmp.length());
int iEnd = strTmp.find(“;”);
strCookiesContent += strTmp.substr(0,iEnd+1);
iStart = strTmp.find(“Set-Cookie:”) + strlen(“Set-Cookie:”);
}
}