概述
- 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";
}