阅读 206

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

场景

????????需要获取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;
}


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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐