请求SpringBoot 服务接口时的中文乱码问题

    此前部署的某SpringBoot的Restful风格服务接口,某个客户端进行请求时出现了中文乱码的问题。

    SpringBoot服务端代码类似如下:

 

    一开始采用了contentType="application/json;charset=utf-8"的解决方法:

                //将xml转为json
                JSONObject xmlToJson = XML.toJSONObject(readXmlContent.toString());

                //设置缩进
                String jsonString = xmlToJson.toString(4);

                //输出格式化后的json
                logger.info(jsonString);
        
                String contentType = "application/json;charset=UTF-8";

                String result = HttpClientUtil.sendPostRequest(jsonString, pmUrl, contentType);     

 其中HttpClientUtil.sendPostRequest的方法如下

 /**
     * 向目标url发送Post请求
     *
     * @param jsonString  请求体Json字符串
     * @param targetUrl  目标URL
     * @param contentType  contentType
     * @return
     */
    public static String sendPostRequest(String jsonString, String targetUrl, String contentType) {

        StringBuilder result = new StringBuilder();

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost postRequest = new HttpPost(targetUrl);

            StringEntity input = new StringEntity(jsonString);
            input.setContentType(contentType);
            postRequest.setEntity(input);
            HttpResponse response = httpClient.execute(postRequest);

            if (response.getStatusLine().getStatusCode() != 200) {
                result.append("HTTP Failed, error code : ").append(response.getStatusLine().getStatusCode());
            }

            BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

            String output;
            logger.info("receive result from Server:{}  \n", targetUrl);
            while ((output = br.readLine()) != null) {
                result.append(output).append("\n");
                logger.info(output);
            }

            httpClient.getConnectionManager().shutdown();

        } catch (Exception e) {

            logger.error(e.getMessage(), e);

        }

        return result.toString();
    }
}

    然后......继续中文乱码,被打脸了。左思右想总觉得哪里不对,代码逐行看过去,终于发现。。。

    没错,就是这个,将请求体封装成StringEntity的时候,要指定编码

    so,关键点根本不在ContentType上, 想当然的解决方案未必能解决实际问题。

    即使问题很小知识很基础,但是见小知大,仍然值得吸取教训。

    

 

转载于:https://www.cnblogs.com/zsfh/p/7689311.html

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值