C++使用curl庫傳送https請求中文亂碼問題
阿新 • • 發佈:2019-01-06
//在資料頭設定字符集為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); }