zoukankan      html  css  js  c++  java
  • 【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 "===========================================
    City = "
                    + 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

  • 相关阅读:
    Git笔记
    排序学习LTR(1):排序算法的评价指标
    C++指针
    C++基础知识笔记
    Shell脚本--菜鸟教程笔记
    torch学习01-入门文档学习
    torch学习02-tensor学习
    torch学习0: 学习概览
    linux基础-用户创建及管理相关
    python-getattr() 函数 dir() 函数
  • 原文地址:https://www.cnblogs.com/guxin/p/csharp-post-request-with-chinese-character.html
Copyright © 2011-2022 走看看