首页 > Web开发 > 详细

libcurl第十四课: 获取返回报文的头部信息

时间:2021-06-01 15:08:08      阅读:29      评论:0      收藏:0      [点我收藏+]

场景

????????需要获取HTTP报头提取Cookie信息,发送给服务器,否则返回302重定向错误

static?size_t?Writeresponse(void?*ptr,?size_t?size,?size_t?nmemb,?void?*userData)
{
string*?pBuffer?=?(string*)userData;
size_t?length?=?size?*?nmemb;
pBuffer->append((char*)ptr,?length);
return?length;
}
int?CCS::LoginEx()
{
	CURL?*hnd?=?curl_easy_init();

	curl_easy_setopt(hnd,?CURLOPT_CUSTOMREQUEST,?"POST");
	curl_easy_setopt(hnd,?CURLOPT_URL,?"http://127.0.0.1:7000/proj/login");

	struct?curl_slist?*headers?=?NULL;
	headers?=?curl_slist_append(headers,?"Postman-Token:?ec3ffce4-5c3c-4786-9396-578ff396c11d");
	headers?=?curl_slist_append(headers,?"cache-control:?no-cache");
	headers?=?curl_slist_append(headers,?"Content-Type:?application/x-www-form-urlencoded");
	curl_easy_setopt(hnd,?CURLOPT_HTTPHEADER,?headers);
	curl_easy_setopt(hnd,?CURLOPT_POSTFIELDS,?"username=slny001&password=Hx%40kj%2319&loginType=2&undefined=");

	std::string?strResponse;
	curl_easy_setopt(hnd,?CURLOPT_WRITEFUNCTION,?Writeresponse);//设置回调函数																			//curl_easy_setopt(pCurlHandle,?CURLOPT_HEADER,?1);//保存HTTP头部信息到strResponseData
	curl_easy_setopt(hnd,?CURLOPT_WRITEDATA,?&strResponse);//设置回调函数的参数,获取反馈信息
	curl_easy_setopt(hnd,?CURLOPT_HEADERFUNCTION,?Writeresponse);//设置回调函数:输出response?headers
	string?responseHeadBuffer;
	curl_easy_setopt(hnd,?CURLOPT_HEADERDATA,?&responseHeadBuffer);//设置回调函数参数
	CURLcode?ret?=?curl_easy_perform(hnd);
	if?(0?==?ret)
	{
		int?nPosOfCookie?=?responseHeadBuffer.find("Cookie:?",?0);
		if?(nPosOfCookie?>?0)
		{
			int?nPosOfEndCookie?=?responseHeadBuffer.find(";",?nPosOfCookie);
			m_cookie?=?responseHeadBuffer.substr(nPosOfCookie?+?7,?nPosOfEndCookie?-?nPosOfCookie?-?7);
		}
	}
	curl_slist_free_all(headers);
	curl_easy_cleanup(hnd);
	return?0;
}


libcurl第十四课: 获取返回报文的头部信息

原文:https://blog.51cto.com/fengyuzaitu/2838964

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!