libcurl第十四课: 获取返回报文的头部信息
  TEZNKK3IfmPf 2023年11月14日 21 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;
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

TEZNKK3IfmPf