天地英雄气,千秋尚凛然。一一刘禹锡
我们的Springboot
已经为我们引用了依赖
但我们还需要一个
1 2 3 4 5 6
| <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> <version>1.19</version> </dependency>
|
首先是一个GET
请求
我们接口使用@RequestParam
接参,所以请求格式应该是http://127.0.0.1:8080/user/say?word=xxx
这样的
代码如下
1 2 3 4 5 6 7 8 9 10
| HttpGet request = new HttpGet(UriBuilder.fromUri("http://127.0.0.1:8080/user/say").queryParam("word", "xxx").build());
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(3000).setMaxRedirects(1).build()).build();
CloseableHttpResponse response = httpClient.execute(request);
String responseData = StreamUtils.copyToString(response.getEntity().getContent(), Charset.defaultCharset());
System.out.println(responseData);
|
执行后可以看到响应回来的数据
如果我们在Java
代码中是@RequestBody
接参,并需要使用Post
方式
这里就可以这样写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| HttpPost request = new HttpPost(UriBuilder.fromUri("http://localhost:8080/user/userList").build());
request.setHeader("Content-Type", "application/json");
PageDTO param = new PageDTO(); param.setPageNum(1); param.setPageSize(20);
request.setEntity(new StringEntity(JSON.toJSONString(param)));
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.DEFAULT).build();
CloseableHttpResponse response = httpClient.execute(request);
String responseData = StreamUtils.copyToString(response.getEntity().getContent(), Charset.defaultCharset());
System.out.println(responseData);
|
响应数据如下
顺便放上APIDocumention