Http post請求數據帶中文參數問題


  Http請求參數帶中文參數時,如{"userName":"用戶名123","password":"123456"}

  請求返回:01-用戶名密碼錯誤

  明明用戶名以及密碼都正確,為啥會不對呢?原來有可能是服務器編碼問題,服務器一般是用UTF-8編碼,需要對post的json字符串進行utf-8轉碼后才能被服務器端識別正確。

  提供轉碼函數:

 ToUtf8轉碼參考 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
wchar_t* AnsiToUnicode(const char* lpszStr)
{
    
wchar_t* lpUnicode;
    
int nLen;

    
if (NULL == lpszStr)
        
return NULL;

    nLen = ::MultiByteToWideChar(CP_ACP, 
0, lpszStr, -1NULL0);
    
if (0 == nLen)
        
return NULL;

    lpUnicode = 
new wchar_t[nLen + 1];
    
if (NULL == lpUnicode)
        
return NULL;

    memset(lpUnicode, 
0sizeof(wchar_t)* (nLen + 1));
    nLen = ::MultiByteToWideChar(CP_ACP, 
0, lpszStr, -1, lpUnicode, nLen);
    
if (0 == nLen)
    {
        
delete[]lpUnicode;
        
return NULL;
    }

    
return lpUnicode;
}

bool UnicodeToUtf8const wchar_t *lpszUnicode, char *lpszUtf8, int nLen )
{
    
int nRet = ::WideCharToMultiByte(CP_UTF8, 0, lpszUnicode, -1, lpszUtf8, nLen, NULLNULL);
    
return (0 == nRet) ? FALSE : TRUE;
}

bool AnsiToUtf8const char *lpszAnsi, char *lpszUtf8, int nLen )
{
    
wchar_t *lpszUnicode = AnsiToUnicode(lpszAnsi);
    
if (NULL == lpszUnicode)
        
return FALSE;

    
int nRet = UnicodeToUtf8(lpszUnicode, lpszUtf8, nLen);

    
delete[]lpszUnicode;

    
return (0 == nRet) ? FALSE : TRUE;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM