概述
- TestRestTemplate 是用于 Restful 请求的模版,并支持异步调用,默认情况下 RestTemplate 依靠 JDK 工具来建立 HTTP 链接,你也可以通过 setRequestFactory 方法来切换不同的 HTTP 库,如 Apache 的 HttpComponents 或 Netty 和 OkHttp
- 通常在入口类或配置类将其注入到IOC容器,它有两个构造方法
默认初始化
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
构造方法中可以传入ClientHttpRequestFactory参数,ClientHttpRequestFactory接口的实现类中存在timeout属性等等
@Bean
RestTemplate restTemplate(){
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(1000);
requestFactory.setReadTimeout(1000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
- 它主要提供了了以下方法,对应不同的 HTTP 请求
HTTP Method | RestTemplate Methods |
---|---|
DELETE | delete |
GET | getForObject、getForEntity |
HEAD | headForHeaders |
OPTIONS | optionsForAllow |
POST | postForLocation、postForObject |
PUT | put |
any | exchange、execute |
GET请求测试
@Test
public void get() throws Exception {
Map<String,String> multiValueMap = new HashMap<>();
multiValueMap.put("username","lake");//传值,但要在url上配置相应的参数
ActResult result = testRestTemplate.getForObject("/test/get?username={username}",ActResult.class,multiValueMap);
Assert.assertEquals(result.getCode(),0);
}
POST请求测试
@Test
public void post() throws Exception {
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","lake");
ActResult result = testRestTemplate.postForObject("/test/post",multiValueMap,ActResult.class);
Assert.assertEquals(result.getCode(),0);
}
文件上传测试
@Test
public void upload() throws Exception {
Resource resource = new FileSystemResource("/home/lake/github/wopi/build.gradle");
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","lake");
multiValueMap.add("files",resource);
ActResult result = testRestTemplate.postForObject("/test/upload",multiValueMap,ActResult.class);
Assert.assertEquals(result.getCode(),0);
}
文件下载测试
@Test
public void download() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set("token","xxxxxx");
HttpEntity formEntity = new HttpEntity(headers);
String[] urlVariables = new String[]{"admin"};
ResponseEntity<byte[]> response = testRestTemplate.exchange("/test/download?username={1}",HttpMethod.GET,formEntity,byte[].class,urlVariables);
if (response.getStatusCode() == HttpStatus.OK) {
Files.write(response.getBody(),new File("/home/lake/github/file/test.gradle"));
}
}
请求头信息测试
@Test
public void getHeader() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set("token","xxxxxx");
HttpEntity formEntity = new HttpEntity(headers);
String[] urlVariables = new String[]{"admin"};
ResponseEntity<ActResult> result = testRestTemplate.exchange("/test/getHeader?username={username}", HttpMethod.GET,formEntity,ActResult.class,urlVariables);
Assert.assertEquals(result.getBody().getCode(),0);
}
PUT请求测试
@Test
public void putHeader() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set("token","xxxxxx");
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","lake");
HttpEntity formEntity = new HttpEntity(multiValueMap,headers);
ResponseEntity<ActResult> result = testRestTemplate.exchange("/test/putHeader", HttpMethod.PUT,formEntity,ActResult.class);
Assert.assertEquals(result.getBody().getCode(),0);
}
- DELETE请求测试
@Test
public void delete() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set("token","xxxxx");
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","lake");
HttpEntity formEntity = new HttpEntity(multiValueMap,headers);
String[] urlVariables = new String[]{"admin"};
ResponseEntity<ActResult> result = testRestTemplate.exchange("/test/delete?username={username}", HttpMethod.DELETE,formEntity,ActResult.class,urlVariables);
Assert.assertEquals(result.getBody().getCode(),0);
}
异步请求
- 异步调用要使用AsyncRestTemplate。 它是RestTemplate的扩展,提供了异步http请求处理的一种机制,通过返回ListenableFuture对象生成回调机制,以达到异步非阻塞发送http请求
public String asyncReq(){
String url = "http://localhost:8080/jsonAsync";
ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {
public void onSuccess(ResponseEntity<JSONObject> result) {
System.out.println(result.getBody().toJSONString());
}
}, new FailureCallback() {
public void onFailure(Throwable ex) {
System.out.println("onFailure:"+ex);
}
});
return "this is async sample";
}