libcurl post 给webserver 中文乱码问题

用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发过来的中文。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值