RestTemplate学习使用

部分学习自转载来源
另一个来自笔者暂时看不懂但觉得很牛逼的网页后来看懂一点点
此链接的拦截器简单易懂一点

RestTemplate
  1. api api地址
  2. 使用步骤
    • 生成RestTemplate对象
      RestTemplate restTemplate = new RestTemplate();
      
    • 调用方法访问接口(例如get接口的getForObject3种方法)
      public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables){}
      public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables)
      public <T> T getForObject(URI url, Class<T> responseType)
      
      String requestPathUrl="http://localhost:8080/get";
      Map<String, ?> uriVariables =new HashMap<>();
      uriVariables.put("id",1);
      List response = restTemplate.getForObject(requestPathUrl, List.class);
      Object o=restTemplate.getForObject("http://localhost:8080/get/{id}",Object.class,"1");
      Object o=restTemplate.getForObject("http://localhost:8080/get/{id}",Object.class,uriVariables);
      
    • 调用方法访问接口(例如get接口的getForEntity3种方法)
      public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables){}
      public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables){}
      public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType){}
      
      Map<String, ?> uriVariables =new HashMap<>();
      uriVariables.put("id",1);
      ResponseEntity<Student> s = restTemplate.getForEntity("http://localhost:8080/get/{id}",Student.class,"1");
      ResponseEntity<Student> s = restTemplate.getForEntity("http://localhost:8080/get/{id}",Student.class,uriVariables);
      
    • 调用方法访问接口(例如post接口的postForEntity3种方法)
      public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
          throws RestClientException {}
      public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
          throws RestClientException {}
      public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {}
      
    • 通过post提交表单数据
      //        post方式提交表单数据
          final String posturi = "http://localhost:8080/post";
          MultiValueMap<String,Object> map= new LinkedMultiValueMap<String,Object>();
          map.add("name","dc");
          map.add("age",13);
          map.add("score",78);
          HttpHeaders headers = new HttpHeaders();
          headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
          HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
          return restTemplate.postForEntity(posturi, request,String.class);
      
    • put和delete方法
       restTemplate.put(posturi,s,params);
       restTemplate.delete ( uri,  params );
      
    • 使用exchange进行访问的例子
      RestTemplate restTemplate = new RestTemplate();
      String url = "http://xxx.top/notice/list";
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
      JSONObject jsonObj = new JSONObject();
      jsonObj.put("start",1);
      jsonObj.put("page",5);
      HttpEntity<String> entity = new HttpEntity<>(jsonObj.toString(), headers);
      ResponseEntity<JSONObject> exchange = restTemplate.exchange(url,
                                        HttpMethod.GET, entity, JSONObject.class);
      System.out.println(exchange.getBody());
      
    • 使用execute提交格式请求,execute为所有请求的底层请求
      execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
      
页顶网页拓展知识
  • resttemplate的初始化
    @Bean
      	public RestTemplate restTemplate() {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(100000);
            requestFactory.setReadTimeout(100000);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            ClientHttpRequestInterceptor ri = new LoggingClientHttpRequestInterceptor();
            List<ClientHttpRequestInterceptor> ris = new ArrayList<ClientHttpRequestInterceptor>();
            ris.add(ri);
            restTemplate.setInterceptors(ris);
            return restTemplate;
        }
    
    解析:新生成一个requestFactory工厂,设置好工厂参数,然后生成RestTemplate,
    生成自己的拦截器,将拦截器加入拦截器列表,
    同时将之设置为resttemplate 的拦截器,然后返回resttemplate
  • 拦截器生成
    public class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
        private static Logger log = LoggerFactory
                .getLogger(LoggingClientHttpRequestInterceptor.class);
    
        @Override
        public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            traceRequest(httpRequest,body);
            ClientHttpResponse response = execution.execute(httpRequest, body);
            traceResponse(response);
            return response;
        }
    
        private void traceRequest(HttpRequest request, byte[] body) {
            try {
                log.debug(
                        "Request URI:{}, Request Body:{}",
                        request.getURI(), new String(body, "UTF-8"));
                // log.info("===========================request begin================================================");
                // log.info("request URI         : {}", request.getURI());
                // log.info("request Method      : {}", request.getMethod());
                // log.info("request Headers     : {}", request.getHeaders() );
                // log.info("request Request body: {}", new String(body, "UTF-8"));
                // log.info("==========================request end================================================");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private void traceResponse(ClientHttpResponse response) throws IOException {
            StringBuilder inputStringBuilder = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"))) {
                String line = bufferedReader.readLine();
                while (line != null) {
                    inputStringBuilder.append(line);
                    inputStringBuilder.append('\n');
                    line = bufferedReader.readLine();
                }
            }
            log.debug("============================response begin==========================================");
            log.debug("Status code  : {}", response.getStatusCode());
            log.debug("Status text  : {}", response.getStatusText());
            log.debug("Headers      : {}", response.getHeaders());
            log.debug("Response body: {}", inputStringBuilder.toString());//WARNING: comment out in production to improve performance
            log.debug("=======================response end=================================================");
        }
    }
    
    解析:继承拦截器,并重写拦截器方法,将之写入日志信息
个人易错tips
  • 表单数据或者对象数据一定要搞清楚,提交方式区别很大
  • 接受数据的类型也要搞清楚,不然会报接受数据错误
  • 如果不是很需要的话,可以直接写resttemplate,不需要拦截器什么的,笔者一开始学都懵了唉
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值