美文网首页
RestTemplate 简单使用

RestTemplate 简单使用

作者: 吉他手_c156 | 来源:发表于2021-12-29 21:33 被阅读0次

    整合 okhttp

    <!‐‐ okhttp3依赖 ‐‐>
    <dependency>        
       <groupId>com.squareup.okhttp3</groupId>
       <artifactId>okhttp</artifactId>
    </dependency>
    

    设置 OkHttp3Clien 为 RestTemplate 客户端,并设置 String 编码

    /**
     * RestTemplate整合OkHttp
     */
    @Configuration
    public class RestTemplateIntegrationOkHttpConfig {
    
        @Bean
        public RestTemplate getRestTemplate(){
            RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
            // 获取消息转换器
            List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
            // 配置 StringHttpMessageConverter ,并设置编码为 utf-8 ,默认是 ISO-8859-1
            messageConverters.set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
            return restTemplate;
        }
    }
    

    常用方法

    URL 后面跟参数

        @Test
        public void sendMsg() throws JsonProcessingException {
            // 请求 url ,url 参数使用 {} 站位符
            String url = "http://localhost:56085/generate?name={1}&effectiveTime={2}";
            // body 请求体
            Map body = new HashMap();
            body.put("mobile",123456789);
            // sms , 30 为 url 路径对应的参数
            ResponseEntity<Map> sms = restTemplate.postForEntity(url, body, Map.class, "sms", "30");
            log.info(sms.getBody().toString());
        }
    

    Rest URL 参数

        @Test
        public void test1() throws JsonProcessingException {
            // 请求 rest URL 
            String url = "http://localhost:56085/test/{name}";
            Map urlParam = new HashMap();
            urlParam.put("name","张三");
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class, urlParam);
            log.info(responseEntity.getBody());
        }
    
    // 或者使用
    
        @Test
        public void test1() throws JsonProcessingException {
            // 请求 rest URL
            String url = "http://localhost:56085/test/{name}";
            Map urlParam = new HashMap();
            urlParam.put("name","张三");
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class, "zhang666");
            log.info(responseEntity.getBody());
        }
    
        @Test
        public void test3(){
    
            String url = "http://localhost:56085/generate?name={1}&effectiveTime={2}";
            Map body = new HashMap();
            body.put("mobile",123456789);
            Map parem = new HashMap();
            parem.put("name","sms");
            parem.put("effectiveTime","30");
    
            HttpEntity httpEntity = new HttpEntity(body);
            ResponseEntity<Map> sms = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class, "sms", "30");
            System.out.println(sms.getBody());
        }
    

    exchange 通用方式

        @Test
        public void test5(){
    
            String url = "http://localhost:56085/test/{name}";
            // 请求体
            Map body = new HashMap();
            body.put("var1","666");
    
            // rest url 变量
            Map urlVarliable = new HashMap();
            urlVarliable.put("name","我爱你中国");
    
            // 设置 header
            HttpHeaders headers = new HttpHeaders();
            headers.set("token","666");
    
            HttpEntity httpEntity = new HttpEntity(body,headers);
            ResponseEntity<Map> sms = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class, urlVarliable);
            System.out.println(sms.getBody());
        }
    

    ParameterizedTypeReference 包装返回类型

    比如接口返回的结构是

    {
      "code": 0,
      "msg": "正常",
      "result": [
        {
          "id": 1,
          "name": "张三"
        },
        {
          "id": 21,
          "name": "李四"
        }
      ]
    }
    

    我们可以定义这样一个类去接受,并指定 ParameterizedTypeReference 的泛型类是这个类,那么返回值就会直接映射为这个类

    @Data
    class Result<T>{
        private Integer code;
        private String msg;
        private T result;
    }
    @Data
    class User{
        private Integer id;
        private String name;
    }
    
        @Test
        public void test6(){
      
            String url = "http://localhost:56085/test/{name}";
            // 请求体
            Map body = new HashMap();
            body.put("var1","666");
    
            // rest url 变量
            Map urlVarliable = new HashMap();
            urlVarliable.put("name","我爱你中国");
    
            // 设置 header
            HttpHeaders headers = new HttpHeaders();
            // 设置请求类型
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("token","666");
    
            HttpEntity httpEntity = new HttpEntity(body,headers);
            // 使用ParameterizedTypeReference进行包装
            // 指定返回值泛型
            ParameterizedTypeReference<Result<List<User>>> reference = new ParameterizedTypeReference<Result<List<User>>>() {};
            ResponseEntity<Result<List<User>>> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference, urlVarliable);\
            // 最终会映射为返回的类型
            Result<List<User>> resut = exchange.getBody();
            System.out.println(resut);
        }
    
    Result(code=0, msg=正常, result=[User(id=1, name=张三), User(id=21, name=李四)])
    

    相关文章

      网友评论

          本文标题:RestTemplate 简单使用

          本文链接:https://www.haomeiwen.com/subject/ewcbqrtx.html