• 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;
        }
  • 相关阅读:
    夺冠概率蓝桥杯
    Memcache配置
    [置顶] 6个月:从小白到程序员,也许没你想的那么难
    Delphi Messagebox自动关闭
    最近读园内的几篇好的文章的摘录及感悟
    近期项目的两点教训
    win7网络连接优先顺序设置方法
    WebSerivce学习笔记
    Delphi 控制摄像头操作
    郁闷的一天
  • 原文地址:https://www.cnblogs.com/libin6505/p/9759274.html
Copyright © 2020-2023  润新知