中文亂碼與locale有關,這裡給出兩種解決方法:
一、設定locale
1、setlocale(LC_ALL, "");//設定程式locale為系統預設(我的系統是zh_CN.utf8),gsoap内部進行編碼轉換依賴于locale,是以必須設定為中文環境。
2、gSoap初始化 gSoap生成的代理類名字為:CSmsProxy
CSmsProxy soapRequest(SOAP_C_MBSTRING);
下面同一般程式設計。gSoap會自動把字元串轉換為正确的編碼。
二、不設定locale,使用預設的"C" locale,程式中傳給gSoap、從gSoap接收的字元串都使用utf8編碼
代理類初始化: CSmsProxy soapRequest(SOAP_C_UTFSTRING);
下面同一般程式設計。gSoap會把字元串當成utf8編碼處理。
下面附帶gb2312與utf8編碼之間的轉換函數:
//gb2312轉utf8
void Gb2312ToUtf8(char* pstrOut, u32 dwOutLen, const char* pstrIn, u32 dwInLen)
{
#ifdef WIN32
int i = MultiByteToWideChar(CP_ACP, 0, pstrIn, -1, NULL, 0);
wchar_t * strSrc = new wchar_t[i+1];
MultiByteToWideChar(CP_ACP, 0, pstrIn, -1, strSrc, i);
i = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, NULL, 0, NULL, NULL);
if (i >= dwOutLen)
{
i = dwOutLen - 1;
}
WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, pstrOut, i, NULL, NULL);
delete strSrc;
#else
iconv_t iConv = iconv_open("utf-8", "gb2312");
iconv(iConv, (char **)&pstrIn, (size_t *)&dwInLen, (char **)&pstrOut, (size_t *)&dwOutLen);
iconv_close(iConv);
#endif
}
//utf8轉gb2312
void Utf8ToGb2312(char* pstrOut, u32 dwOutLen, const char* pstrIn, u32 dwInLen)
if (NULL == pstrOut)
return ;
int i = MultiByteToWideChar(CP_UTF8, 0, pstrIn, -1, NULL, 0);
MultiByteToWideChar(CP_UTF8, 0, pstrIn, -1, strSrc, i);
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, pstrOut, i, NULL, NULL);
iconv_t iConv = iconv_open("gb2312", "utf-8");
}
//gb2312轉Unicode
void Gb2312ToUnicode(wchar_t* pstrOut, u32 dwOutLen, const char* pstrIn, u32 dwInLen)
u32 i = MultiByteToWideChar(CP_ACP, 0, pstrIn, -1, NULL, 0);
MultiByteToWideChar(CP_ACP, 0, pstrIn, -1, pstrOut, i);
iconv_t iConv = iconv_open("unicode", "gb2312");
iconv(iConv, (char**)pstrIn, &dwInLen, (char**)pstrOut, &dwOutLen);
//Unicode轉Gb2312
void UnicodeToGb2312(char* pstrOut, u32 dwOutLen, const wchar_t* pstrIn, u32 dwInLen)
u32 i = WideCharToMultiByte(CP_ACP, 0, pstrIn, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, pstrIn, -1, pstrOut, i, 0, 0);
iconv_t iConv = iconv_open("gb2312", "unicode");
//utf8轉Unicode
void Utf8ToUnicode(wchar_t* pstrOut, u32 dwOutLen, const char* pstrIn, u32 dwInLen)
u32 i = MultiByteToWideChar(CP_UTF8, 0, pstrIn, -1, NULL, 0);
MultiByteToWideChar(CP_UTF8, 0, pstrIn, -1, pstrOut, i);
iconv_t iConv = iconv_open("unicode", "utf-8");