zoukankan      html  css  js  c++  java
  • 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 + "	password: "+password;
            System.out.println(result);
            return result;
        }
  • 相关阅读:
    python 如何将md5转为16字节
    linux非root用户执行开机启动程序
    python 正则表达式的使用
    Go随机数的使用
    Go 的类型断言type assertion
    go get中的...
    Go语言圣经
    python入门第三十五天--事件驱动模型(补)练习理解
    MySQL_Ubuntu安装
    JAVA入门基础--数据类型
  • 原文地址:https://www.cnblogs.com/libin6505/p/9759274.html
Copyright © 2011-2022 走看看