Spring学习笔记(三十五):关于httpClient的post请求,到后台中文乱码的问题

来源:互联网 发布:ubuntu 修改apt get源 编辑:程序博客网 时间:2024/05/16 06:47
  • 问题描述:用HttpClient的post进行请求,发现如果post的数据中有中文,那么到后台存进数据库的时候就会乱码;
  • 原因分析:是编码问题
  • 解决办法:在提交数据的时候,进行编码UTF-8
    代码如下:
public static String postJson(String url,String jsonString) throws Exception{        CloseableHttpClient httpClient = HttpClients.createDefault();        HttpPost httpPost = new HttpPost(url);        //下面这里要加个编码参数:UTF-8,否则提交到接口后,中文会乱码        StringEntity strEntity = new StringEntity(jsonString,"UTF-8");        httpPost.setEntity(strEntity);        String result = "";        try{            CloseableHttpResponse response = httpClient.execute(httpPost);            HttpEntity httpEntity = response.getEntity();            result = EntityUtils.toString(httpEntity,"UTF-8");        }finally{            httpClient.close();        }        return result;    }
阅读全文
0 0