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