天天看點

libcurl 庫處理url連結字元串包含中文導緻執行失敗問題

1、問題

通常見到的url連結位址一般都是不包含中文的或者已經将中文轉碼過的,但有些情況下仍然有中文情況,這時候使用curl_easy_setopt(curl, CURLOPT_URL, sUrl.c_str());會執行失敗,是以需要想辦法進行字元串編碼。剛開始是将url進行了拼接轉換,例如下面:

std::wstring wsfilepath;
std::wstring wsUrl = L"http://127.0.0.1:80/project/fileupload/filepath";
wsUrl = wsUrl + L"?filepath=" + wsfilepath;
std::string sURL = StringConvert::string2wstring(wsUrl);
curl_easy_setopt(curl, CURLOPT_URL, sURL .c_str());
           

但是發現wsfilepath中包含中文時執行失敗,應該還是編碼轉換的問題。查資料以後找到如下解決方案:

2、解決方法

利用如下先編碼後組合成url的方式:

std::wstring wsUrl = L"http://127.0.0.1:80/project/fileupload/filepath"
	std::string sUrl = StringConvert::wstring2string(wsUrl);
	std::string sfileName = StringConvert::wstring2string(wsfileName);
	
	CURL *curl = curl_easy_init();;
	char* encode_sfileName = curl_easy_escape(curl, sfileName.c_str(), 0);
	string e_sfileName = encode_sfileName;
	sUrl = sUrl + "?fileName=" + e_sfileName;
	curl_easy_cleanup(curl);
	curl_free(encode_sfileName);
………………
    curl_easy_setopt(curl, CURLOPT_URL, sURL .c_str());
           

繼續閱讀