C++使用curl库发送https请求中文乱码问题

 //在数据头设置字符集为UTF-8,解决中文乱码问题
        struct curl_slist *head = NULL;
	head = curl_slist_append(head, "Content-Type:application/x-www-form-urlencoded;charset=UTF-8");
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, head);

最后记得

curl_slist_free_all(head);//记得要释放




源码

void CCheckDlg::SendDataToHttp(CString csOfficeID, CString csOperaCMD, CString csScreenType, CString & csValue)
{
	CURL *curl;
	CURLcode ret;
	int  wr_error;
	wr_error = 0;
	wr_index = 0;

	curl = curl_easy_init();
	if (curl == NULL) 
	{
	   return ;
	}

    //在数据头设置字符集为UTF-8,解决中文乱码问题
	struct curl_slist *head = NULL;
	head = curl_slist_append(head, "Content-Type:application/x-www-form-urlencoded;charset=UTF-8");
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, head);

    //指定URL
	curl_easy_setopt( curl, CURLOPT_URL, "https://********************.json" );

    //双向认证
	CString csCerpath, csKeypath;
	csCerpath = m_csPath + "cert/sesanclientCerts.pem";
	csKeypath = m_csPath + "cert/sesanclient.pem";
	curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,false);  
	curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,false); 
	curl_easy_setopt(curl,CURLOPT_SSLCERT,csCerpath);  
	curl_easy_setopt(curl,CURLOPT_SSLCERTPASSWD,"sesanqueue");  
	curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");  
	curl_easy_setopt(curl,CURLOPT_SSLKEY,csKeypath);  
	curl_easy_setopt(curl,CURLOPT_SSLKEYPASSWD,"sesanqueue");  
	curl_easy_setopt(curl,CURLOPT_SSLKEYTYPE,"PEM");  

	
	CString csResult;
	csResult.Format("officeId=%s&doctorId=%s&type=%s&operateCMD=%s&operateObjectType=%s&screenType=%s&noonType=%s&doctorType=%s&stringValue=%s",csOfficeID,"","12",csOperaCMD,"STRING",csScreenType,"4","0",csValue);
	string strResult(csResult.GetBuffer(csResult.GetLength()));
	csResult.ReleaseBuffer();

    //编码转换
	string strData;
	GB2312ToUTF_8(strData, strResult.c_str(), strResult.size());
	char szJsonData[1024];  
	memset(szJsonData, 0, sizeof(szJsonData)); 
	strcpy(szJsonData, strData.c_str()); 
 	
	//设置https请求参数
	curl_easy_setopt(curl, CURLOPT_POST, true);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, szJsonData);
	curl_easy_setopt( curl, CURLOPT_WRITEDATA, (void *)&wr_error );
	curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_data );

	ret = curl_easy_perform( curl );

	//返回
	if (ret != CURLE_OK)
	{
// 		CString cserror;
// 		cserror.Format("curl_easy_perform() failed: %s", curl_easy_strerror(ret));
// 		AfxMessageBox(cserror);
	}
	
	curl_slist_free_all(head);//记得要释放

	curl_easy_cleanup(curl);
}


你可能感兴趣的:(C++,网络编程)