• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

【C#】POST请求参数含中文,服务器解析得到乱码

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

问题: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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
(翻译)C#中的SOLID原则–开放/封闭原则发布时间:2022-07-18
下一篇:
C#调用Outlook发送邮件发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap