1、服务端代码:
@RequestMapping("getUsers")
public List<User> getUsers(){
List<User> users = new ArrayList<>();
users.add(new User(1,"ss","123","ss"));
users.add(new User(2,"jack","333","ff"));
users.add(new User(3,"rose","444","gg"));
return users;
}
- httpclient代码
/**
* 使用httpclient获取集合
*/
@Test
public void testgetUsers(){
try {
//1.构建http对象(相当于浏览器)
CloseableHttpClient httpClient = HttpClients.createDefault();
//3.创建http post请求对象
HttpPost post = new HttpPost("http://localhost:18081/testBoot/getUsers");
/**
* 3.1添加请求参数,post请求参数是在body中
* NameValuePair:封装参数的接口
* BasicNameValuePair: 接口实现类
*/
List<NameValuePair> params = new ArrayList<>();
/**
* 创建httpentity接口的文本实现类对象
* 封装参数并设置编码
*/
HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
post.setEntity(httpEntity);//设置参数体
//4.创建响应对象
CloseableHttpResponse response = httpClient.execute(post);
/**
* 由于响应接口返回的是一个字符串,因此需要转换
* 响应体数据封装在HttpEntity对象中
*/
String s = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(s);
//5.释放资源
response.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
- 测试结果:
23:55:43.776 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://localhost:18081][total kept alive: 1; route allocated: 1 of 2; total allocated: 1 of 20]
[{"id":1,"userName":"ss","passWord":"123","realName":"ss"},{"id":2,"userName":"jack","passWord":"333","realName":"ff"},{"id":3,"userName":"rose","passWord":"444","realName":"gg"}]
23:55:43.776 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager is shutting down