【C#】POST請求參數含中文,服務器解析得到亂碼


問題:POST請求參數含有中文,已將含中文的string以UTF-8編碼格式轉為byte[],並寫入到請求流中,但服務器收到數據后以UTF-8解碼,得到的依然是亂碼!

百度到了以下方法,但依然無法解決問題:

byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());

因為問題根本不在這里,而是在必須寫上ContentType,並指明字符集 。

同時總結POST請求的寫法。


聯網工具類:

/// <summary>
/// 帶參的POST請求,傳遞文本數據
/// </summary>
/// <param name="url">例如 192.168.1.222:8080/getMaterialsBySpacePlanIdToClient</param>
/// <param name="parameters"></param>
/// <returns></returns>
public string HttpPostRequest(string url, IDictionary<string, string> parameters)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GlobalVariable.SERVER_ADDRESS_TEMP + url);
    httpWebRequest.Method = "POST";
    httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf8"; // 必須指明字符集!
    httpWebRequest.Timeout = 20000;

    // 參數
    if (!(parameters == null || parameters.Count == 0))
    {
        StringBuilder buffer = new StringBuilder();
        int i = 0;
        foreach (string key in parameters.Keys)
        {
            if (i > 0)
            {
                buffer.AppendFormat("&{0}={1}", key, parameters[key]);
            }
            else
            {
                buffer.AppendFormat("{0}={1}", key, parameters[key]);
            }
            i++;
        }
        // 給文本數據編碼
        byte[] data = Encoding.UTF8.GetBytes(buffer.ToString()); // 必須與ContentType中指定的字符集一致!

        // 往請求的流里寫數據
        using (Stream stream = httpWebRequest.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
    }

    // 從響應對象中獲取數據
    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
    string responseContent = streamReader.ReadToEnd();

    streamReader.Close();
    httpWebResponse.Close();
    httpWebRequest.Abort();

    return responseContent;
}

/// <summary>
/// 無參的POST請求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string HttpPostRequest(string url)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GlobalVariable.SERVER_ADDRESS_TEMP + url);
    httpWebRequest.ContentType = "application/x-www-form-urlencoded"; // 因為POST無參,不寫字符集也沒問題
    httpWebRequest.Method = "POST";
    httpWebRequest.Timeout = 20000;

    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
    string responseContent = streamReader.ReadToEnd();

    streamReader.Close();
    httpWebResponse.Close();
    httpWebRequest.Abort();

    return responseContent;
}

調用以上方法

// 獲取數據
private void GetCityAndCommunityJsonData()
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    dic.Add("provinceName", "廣西壯族自治區"); 
    string request = GlobalVariable.GET_CITYS_BY_PROVINCE_TO_CLIENT;
    string json = NetworkUtils.Instance.HttpPostRequest(request, dic);
    System.Console.WriteLine("完成:獲取城市/小區數據");

    // 將Json反序列化為對應的對象集合
    list = JsonConvert.DeserializeObject<List<CityAndCommunity>>(json);
    for (int i = 0; i < list.Count; i++)
    {
        System.Console.WriteLine(list[i].ToString());
    }
}

// 實體類
class CityAndCommunity
{
    public string City { get; set; }
    public string[] Community { get; set; }

    public override string ToString()
    {
        if (Community != null)
        {
            string communityStr = "";
            for (int i = 0; i < Community.Length; i++)
            {
                if (i != Community.Length - 1)
                {
                    communityStr += Community[i] + " , ";
                }
                else
                {
                    communityStr += Community[i].ToString();
                }
            }
            return "===========================================\nCity = "
                + City + " , communityStr = " + communityStr;
        }
        return base.ToString();
    }
}

坑點:

  • 必須加上httpWebRequest.ContentType = “application/x-www-form-urlencoded;charset=utf8”; 其中字符集也可以是gb2312,只要跟給文本數據編碼采用同樣格式即可。

極其重要的參考:

http://46aae4d1e2371e4aa769798941cef698.devproxy.yunshipei.com/u011185231/article/details/52090334


免責聲明!

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



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