Spring Boot:RestTemplate

川长思鸟来 2021-10-01 09:38 417阅读 0赞

概述

  • TestRestTemplate 是用于 Restful 请求的模版,并支持异步调用,默认情况下 RestTemplate 依靠 JDK 工具来建立 HTTP 链接,你也可以通过 setRequestFactory 方法来切换不同的 HTTP 库,如 Apache 的 HttpComponents 或 Netty 和 OkHttp
  • 通常在入口类或配置类将其注入到IOC容器,它有两个构造方法

默认初始化

  1. @Bean
  2. public RestTemplate restTemplate(){
  3. return new RestTemplate();
  4. }

构造方法中可以传入ClientHttpRequestFactory参数,ClientHttpRequestFactory接口的实现类中存在timeout属性等等

  1. @Bean
  2. RestTemplate restTemplate(){
  3. SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
  4. requestFactory.setConnectTimeout(1000);
  5. requestFactory.setReadTimeout(1000);
  6. RestTemplate restTemplate = new RestTemplate(requestFactory);
  7. return restTemplate;
  8. }
  • 它主要提供了了以下方法,对应不同的 HTTP 请求





































HTTP Method RestTemplate Methods
DELETE delete
GET getForObject、getForEntity
HEAD headForHeaders
OPTIONS optionsForAllow
POST postForLocation、postForObject
PUT put
any exchange、execute

GET请求测试

  1. @Test
  2. public void get() throws Exception {
  3. Map<String,String> multiValueMap = new HashMap<>();
  4. multiValueMap.put("username","lake");//传值,但要在url上配置相应的参数
  5. ActResult result = testRestTemplate.getForObject("/test/get?username={username}",ActResult.class,multiValueMap);
  6. Assert.assertEquals(result.getCode(),0);
  7. }

POST请求测试

  1. @Test
  2. public void post() throws Exception {
  3. MultiValueMap multiValueMap = new LinkedMultiValueMap();
  4. multiValueMap.add("username","lake");
  5. ActResult result = testRestTemplate.postForObject("/test/post",multiValueMap,ActResult.class);
  6. Assert.assertEquals(result.getCode(),0);
  7. }

文件上传测试

  1. @Test
  2. public void upload() throws Exception {
  3. Resource resource = new FileSystemResource("/home/lake/github/wopi/build.gradle");
  4. MultiValueMap multiValueMap = new LinkedMultiValueMap();
  5. multiValueMap.add("username","lake");
  6. multiValueMap.add("files",resource);
  7. ActResult result = testRestTemplate.postForObject("/test/upload",multiValueMap,ActResult.class);
  8. Assert.assertEquals(result.getCode(),0);
  9. }

文件下载测试

  1. @Test
  2. public void download() throws Exception {
  3. HttpHeaders headers = new HttpHeaders();
  4. headers.set("token","xxxxxx");
  5. HttpEntity formEntity = new HttpEntity(headers);
  6. String[] urlVariables = new String[]{"admin"};
  7. ResponseEntity<byte[]> response = testRestTemplate.exchange("/test/download?username={1}",HttpMethod.GET,formEntity,byte[].class,urlVariables);
  8. if (response.getStatusCode() == HttpStatus.OK) {
  9. Files.write(response.getBody(),new File("/home/lake/github/file/test.gradle"));
  10. }
  11. }

请求头信息测试

  1. @Test
  2. public void getHeader() throws Exception {
  3. HttpHeaders headers = new HttpHeaders();
  4. headers.set("token","xxxxxx");
  5. HttpEntity formEntity = new HttpEntity(headers);
  6. String[] urlVariables = new String[]{"admin"};
  7. ResponseEntity<ActResult> result = testRestTemplate.exchange("/test/getHeader?username={username}", HttpMethod.GET,formEntity,ActResult.class,urlVariables);
  8. Assert.assertEquals(result.getBody().getCode(),0);
  9. }

PUT请求测试

  1. @Test
  2. public void putHeader() throws Exception {
  3. HttpHeaders headers = new HttpHeaders();
  4. headers.set("token","xxxxxx");
  5. MultiValueMap multiValueMap = new LinkedMultiValueMap();
  6. multiValueMap.add("username","lake");
  7. HttpEntity formEntity = new HttpEntity(multiValueMap,headers);
  8. ResponseEntity<ActResult> result = testRestTemplate.exchange("/test/putHeader", HttpMethod.PUT,formEntity,ActResult.class);
  9. Assert.assertEquals(result.getBody().getCode(),0);
  10. }
  • DELETE请求测试

    @Test

    1. public void delete() throws Exception {
    2. HttpHeaders headers = new HttpHeaders();
    3. headers.set("token","xxxxx");
    4. MultiValueMap multiValueMap = new LinkedMultiValueMap();
    5. multiValueMap.add("username","lake");
    6. HttpEntity formEntity = new HttpEntity(multiValueMap,headers);
    7. String[] urlVariables = new String[]{"admin"};
    8. ResponseEntity<ActResult> result = testRestTemplate.exchange("/test/delete?username={username}", HttpMethod.DELETE,formEntity,ActResult.class,urlVariables);
    9. Assert.assertEquals(result.getBody().getCode(),0);
    10. }

异步请求

  1. - 异步调用要使用AsyncRestTemplate 它是RestTemplate的扩展,提供了异步http请求处理的一种机制,通过返回ListenableFuture对象生成回调机制,以达到异步非阻塞发送http请求
  2. public String asyncReq(){
  3. String url = "http://localhost:8080/jsonAsync";
  4. ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
  5. future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {
  6. public void onSuccess(ResponseEntity<JSONObject> result) {
  7. System.out.println(result.getBody().toJSONString());
  8. }
  9. }, new FailureCallback() {
  10. public void onFailure(Throwable ex) {
  11. System.out.println("onFailure:"+ex);
  12. }
  13. });
  14. return "this is async sample";
  15. }

发表评论

表情:
评论列表 (有 0 条评论,417人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringSpring 事务

    一、事务 1.1 概念 > 事务是指数据库操作的最小工作单元,是作为单个逻辑工作单元执行的一系列操作,这些操作作为一个整体一起向系统提交,要么都执行,要么都不执行。