环境:windows,VS多字节字符集
1、请求后端数据解码:
string UTF8ToGB(const char* str) {
string result;
WCHAR *strSrc;
LPSTR szRes;
int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i + 1];
MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i + 1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete[]strSrc;
delete[]szRes;
return result;
}
string data = UTF8ToGB(root["data"].asString().c_str());
2、使用 url 编码数据,发送请求给后端
string urlEncode(const char *sIn) {
string sOut;
for (size_t ix = 0; ix < strlen(sIn); ix++) {
unsigned char buf[4];
memset(buf, 0, 4);
if (isalnum((unsigned char)sIn[ix])) {
buf[0] = sIn[ix];
} else {
buf[0] = '%';
buf[1] = toHex((unsigned char)sIn[ix] >> 4);
buf[2] = toHex((unsigned char)sIn[ix] % 16);
}
sOut += (char *)buf;
}
return sOut;
};
string name = "名字";
string url = "http://domain.test/?name="
Json::Value arrayObj;
arrayObj.append(urlEncode(name.c_str()));
url += arrayObj.toStyledString();
// 多字节编码环境下,CString 转换成 string 再进行 url 编码
// CString name = "名字";
// string name1 = name.GetBuffer(0);
// string result = urlEncode(name1.c_str())
3、Python2 URL 中文解码
如果源URL编码的字符串是 unicode,需要转换成 str 再进行解码
from urllib import unquote
unquote(source.encode('utf8')).decode('gb2312')