乱码 - httpclient获取返回结果中文变问号

查看:567
本文介绍了乱码 - httpclient获取返回结果中文变问号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

public static String saveLog(JSONObject jsonParams) throws IOException {
        
        logger.info("save log params : " + jsonParams.toString());
        logger.debug(Instant.now().toString());

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost("http://localhost:8080/log/httpservice/saveLog");
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        httpPost.addHeader("Accept", "application/json");
//        httpPost.addHeader("Accept-Language", "zh-CN");

        StringEntity requestEntity = new StringEntity(jsonParams.toString(), "utf-8");
        requestEntity.setContentEncoding("UTF-8");
        requestEntity.setContentType("application/json; charset=utf-8");
        httpPost.setEntity(requestEntity);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        
        httpPost.releaseConnection();
        httpClient.close();
        
        logger.info("save log result : " + result);
        logger.debug(Instant.now().toString());

        return result;
    }

功能就是调用一个服务端的http接口记录一次日志信息,经设置服务端可以获取到中文参数并处理,现在的问题是客户端程序这边获取到的返回结果中包含的中文结果反馈变成了问号。
这是服务端控制台打印结果

result = {"success":true,"message":"用户操作日志记录完成","detail":""}

这是客户端获取到的结果打印情况

save log result : {"success":true,"message":"??????????","detail":""}

服务端接收请求处理代码

    @ResponseBody
    @RequestMapping(value = "/saveLog", method = RequestMethod.POST)
    public String saveLog(@RequestBody String requestBody) {
        logger.info("requestBody = " + requestBody);
        JsonObject jsonObject = new JsonParser().parse(requestBody).getAsJsonObject();
        
        String result = this.save(jsonObject);
        logger.info("result = " + result);
        return result;
    }

解决方案

又是自问自答,好忧伤。难道社区里的小伙伴都没有碰到过类似的问题嘛!
其实代码没有任何问题,貌似是maven配置引入的jar包有问题。重点在于,maven配置本身没有问题,此时无论怎样重新构建项目都没有用,包括clean project, maven update等操作,都是没效果的,只有把自己的maven配置目录m2文件夹中该项目会用到的所有jar包全部删掉,然后让eclipse重新下载一次这些jar包,就可以用了。
这已经是我第二次遇到一样删maven m2目录的情况了,略微有点心疼自己

这篇关于乱码 - httpclient获取返回结果中文变问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆