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;
    }

猜你喜欢

转载自www.cnblogs.com/libin6505/p/9759274.html
今日推荐