RestTemplate 简单使用

整合 okhttp


        
   com.squareup.okhttp3
   okhttp

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

/**
 * RestTemplate整合OkHttp
 */
@Configuration
public class RestTemplateIntegrationOkHttpConfig {

    @Bean
    public RestTemplate getRestTemplate(){
        RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        // 获取消息转换器
        List> 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 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 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 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 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 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{
    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>> reference = new ParameterizedTypeReference>>() {};
        ResponseEntity>> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, reference, urlVarliable);\
        // 最终会映射为返回的类型
        Result> resut = exchange.getBody();
        System.out.println(resut);
    }
Result(code=0, msg=正常, result=[User(id=1, name=张三), User(id=21, name=李四)])

RestTemplate 提交 form 形式 application/x-www-form-urlencoded

form表单的提交只需要需要把头信息ContentType 设置为MediaType.APPLICATION_FORM_URLENCODED ,同时参数需要使用 MultiValueMap 封装。如下所示:

        MultiValueMap body = new LinkedMultiValueMap<>();
        body.add("grant_type", "authorization_code");
        body.add("redirect_uri", "http://127.0.0.1:9091/client1/callback");
        body.add("client_id", "c1");
        body.add("client_secret", "123456");
        body.add("code", code);

        HttpHeaders headers = new HttpHeaders();
        // 设置 header application/x-www-form-urlencoded
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity httpEntity = new HttpEntity(body, headers);

        ResponseEntity sms = restTemplate.exchange(token, HttpMethod.POST, httpEntity, Map.class);
        System.out.println(sms.getBody());

        ResponseEntity mapResponseEntity = restTemplate.postForEntity(token, httpEntity, Object.class);
 

                            
                        
                    
                    
                    

你可能感兴趣的:(RestTemplate 简单使用)