欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot-RestTemplate

程序员文章站 2024-02-29 19:11:22
...

RestTemplate是spring提供的访问Rest服务的客户端,默认使用jdk的http连接工具(HttpURLConnection)。可以通过setRequestFactory属性切换到其它http源, Apache HttpComponentsNettyOkHttp等。

一、入口

入口方法主要根据HTP的六个方法制定的:

HTTP method RestTempalte methods
GET getForObject
- getForENtity
POST poetForLocation
- postForObject
DELETE delete
PUT put
HEAD headForHeaders
OPTIONS optionsForAllow
通用方法 exchange
- execute

注:默认使用HttpMessageConverter实例完成POJPHTTP的转换,也可以通过setMessageConverters注册其它的转换器。(@ResponseBody使用的也是HttpMessageConverter

二、GET

getForObject()getForEntity()

getForObject()方法

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)

注:getForObject()比getForEntity()多了HTTP转换成POJO,但是省略了response信息。

getForObject()方法实例
public void restTemplateGetTest(){
  RestTemplate restTemplate = new RestTemplate();
//无参
  MessObj messObj1 = restTemplate.getForObject("http://xxx.com/test",MessObj .class);
//占位符传参
  MessObj messObj2 = restTemplate.getForObject("http://xxx.com/test/{1}/{2}",MessObj .class,"参数1","参数2");
//map传参
  Map<String,String> map = new HashMap();
  map.put("id","1");
  map.put("name","zs")
  MessObj messObj1 = restTemplate.getForObject("http://xxx.com/test",MessObj .class,map);
//结果:messObj{status=200,data=[{a=1}...]...}
}

getForEntity()方法

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){}

注:返回的是ResponseEntity对象,需要json工具解析成pojoResponseEntityHttpStatus getStatusCode()BodyBuildercreated(URI location)等方法,方便查看更多信息。
ResponseEntity.java

public HttpStatus getStatusCode(){}
public int getStatusCodeValue(){}
public boolean equals(@Nullable Object other) {}
public String toString() {}
public static BodyBuilder status(HttpStatus status) {}
public static BodyBuilder ok() {}
public static <T> ResponseEntity<T> ok(T body) {}
public static BodyBuilder created(URI location) {}
...

HttpStatus.java

public enum HttpStatus {
public boolean is1xxInformational() {}
public boolean is2xxSuccessful() {}
public boolean is3xxRedirection() {}
public boolean is4xxClientError() {}
public boolean is5xxServerError() {}
public boolean isError() {}
}

BodyBuilder.java

public interface BodyBuilder extends HeadersBuilder<BodyBuilder> {
    //设置正文的长度,以字节为单位,由Content-Length标头
      BodyBuilder contentLength(long contentLength);
    //设置body的MediaType 类型
      BodyBuilder contentType(MediaType contentType);
    //设置响应实体(ResponseEntity)的主体(内容)并返回它。
      <T> ResponseEntity<T> body(@Nullable T body);
}

getForEntity()方法实例:

public void gettTest(){
    RestTemplate resTemplate = new RestTemplate();
    ResponseEntity<MessObj> entity = restTemplate.getForEntity("http://xx.com/test",MessObj.class);
    HttpStatus hsc = entity.getStatusCode();
    MessObj msObj = entity.getBody();
    ResponseEntity.BodyBuilder status = ResponseEntity.status(hsc);
}

三、POST

postForObject()postForEntity()

postForObject方法
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 {}

实例

public void postTest(){
    RestTemplate restTemplate = new RestTemplate();
    //第一个参数url
    String url = "http://xxx.com/test";
    //第二个参数request(val,header)
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType);
    //一个key对应多个val的map
    MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
    map.add("name", "zhangsan");    
    //request
    HttpEntity<MultiValueMap<String,String>> request = new HttpEntity<>(map,headers);
    //执行 url,http主
    ResponseEntity<String> response = restTemplate.postForEntity(url,request,String.class);
    //返回值{"status":500,"msg":"xxx","data":null}
    System.out.println(response.getBody());
}

头类型
MediaType

json : application/json
xml : application/xml
png : image/png
jpg : image/jpeg
gif : imge/gif

excute()和exchange()

excute()返回映射对象<T>,exchange()返回ResponseEntity<T>

restTemplate.exchange(
         String url, //地址
         HttpMethod method,//请求类型(HttpMethod.POST/PUT/DELETE/GET)
         HttpEntity requestEntity, //请求主体:请求体、头、内容
         Class responseType, //返回实体类
         Object uriVariables[]//url参数
     )

转载于:https://www.jianshu.com/p/57d8b2a034d6