httpclient post请求带参数返回数据乱码问题解决

 

客户端代码:

复制代码
//带参数的post请求
    @Test
    public void doPostWithParam() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建一个post对象
        HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
        //模拟一个表单
        List<NameValuePair> kvList = new ArrayList<NameValuePair>();
        kvList.add(new BasicNameValuePair("username", "张三"));
        kvList.add(new BasicNameValuePair("password", "123"));
        //包装成一个Entity对象(后面加字符集是为了向服务端发送数据时不会乱码)
        StringEntity paramEntity = new UrlEncodedFormEntity(kvList,"utf-8");
        //设置请求内容
        post.setEntity(paramEntity);
        //执行post请求
        CloseableHttpResponse response = httpClient.execute(post);
        HttpEntity rtnEntity = response.getEntity();
        String string = EntityUtils.toString(rtnEntity, "utf-8");
        System.out.println(string);
        response.close();
        httpClient.close();
    }
复制代码

 

服务端Controller代码:

复制代码
    //mapping后面加produces是为了返回数据给接口调用者时不会乱码
    @RequestMapping(value="/httpclient/post",method=RequestMethod.POST,
            produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
    @ResponseBody
    public String testPost(String username,String password) {
        String result = "username: "+username + "\tpassword: "+password;
        System.out.println(result);
        return result;
    }
复制代码

 

posted @   戈博折刀  阅读(6084)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示