在使用httpclient发送post请求的时候,接收端中文乱码问题解决。

    我们都知道,一般情况下使用post请求是不会出现中文乱码的。可是在使用httpclient发送post请求报文含中文的时候在发送端数据正常但是到了服务器端就中文乱码了。

    解决办法:

    发送端进行设置编码如下:
    009.png

    主要代码:

    1. if (null != jsonParam) {
    2. //解决中文问题。
    3. method.addHeader("Content-type","application/json; charset=utf-8");
    4. method.setHeader("Accept", "application/json");
    5. method.setEntity(new StringEntity(jsonParam.toString(), Charset.forName("UTF-8")));
    6. }
    7. HttpResponse result = httpClient.execute(method);

    在接收(服务器)端:
    010.png

    主要代码:

    1. @RequestMapping(value = "getJson")
    2. @ResponseBody
    3. public Map<String,Object> getJson(@RequestBody String requestBody, HttpServletRequest request){
    4. requestBody = new String(requestBody.getBytes(), Charset.forName("utf-8"));
    5. JSONObject jsonObject = JSONObject.parseObject(requestBody);
    6. System.out.println(jsonObject);
    7. ResultJsonInfo info = JSONObject.parseObject(jsonObject.toJSONString(), ResultJsonInfo.class);
    8. System.out.println(info);
    9. //TODO 处理自己业务
    10. JSONObject result= new JSONObject();
    11. result.put("success", "true");
    12. Map<String, Object> resultMap = new HashMap<String, Object>();
    13. resultMap.put("isok", true);
    14. return resultMap;
    15. }