用libcurl进行http client 开发。采用post发送数据给webserver。发现有中文的时候,对方收到的是乱码。这个问题通过下面解决
/* 加了下面这3行,这样web服务端不会收到乱码,不加的话,webserver 需要设置header("Content-type:text/html;charset=utf-8");这样对方能收到中文字*/
struct curl_slist *head = NULL;
head = curl_slist_append(head,"Content-type:text/html;charset=utf-8");
curl_easy_setopt(curl, CURLOPT_HEADER, head);
这样的话,webserver不用设置header,设置的话也没关系。
还有就是webserver返回中文的时候。因为web一般都是utf-8模式,所以需要进行utf-8转unicode【我是unicode工程】
wstring Utf8ToUnicode(const string &utf8_str)
{
int len;
len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)utf8_str.c_str(), -1, NULL,0);
WCHAR * wszUnicode = new WCHAR[len+1];
memset(wszUnicode, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)utf8_str.c_str(), -1, wszUnicode, len);
wstring unicodeWstring(wszUnicode);
delete wszUnicode;
return unicodeWstring;
}
void CMainDlg::Onmakesureshuiying()
{
string strResponse;
string strPostResult;
httpclient client;
strPostResult="< postdata data=post a data to you 中国!></postdata>";
client.Post("http://127.0.0.1/res.php",strPostResult,strResponse);
//MessageBoxW(NULL,UTF8ToUnicode(strResponse).c_str(),L"http://www.baidu.com",MB_OK);
printf(strResponse.c_str());
STRACE(L"%s",strResponse);
MessageBoxW(NULL,Utf8ToUnicode(strResponse).c_str(),NULL,MB_OK);
}
这样转换之后,客户端能正确显示webserver发过来的中文。