使用Spring的RestTemplate發(fā)送Http請(qǐng)求

使用Spring的RestTemplate發(fā)送Http請(qǐng)求

1,Spring的RestTemplate

1.1 基礎(chǔ)概念

Spring用于同步client端的核心類,簡(jiǎn)化了與http服務(wù)的通信,并滿足RestFul原則,程序代碼可以給它提供URL,并提取結(jié)果。默認(rèn)情況下,RestTemplate默認(rèn)依賴jdk的HTTP連接工具。當(dāng)然你也可以 通過setRequestFactory屬性切換到不同的HTTP源,比如Apache HttpComponents、NettyOkHttp。

RestTemplate能大幅簡(jiǎn)化了提交表單數(shù)據(jù)的難度,并且附帶了自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)的功能,但只有理解了HttpEntity的組成結(jié)構(gòu)(header與body),且理解了與uriVariables之間的差異,才能真正掌握其用法。

  • 該類的入口主要是根據(jù)HTTP的六個(gè)方法制定:
HTTP method RestTemplate methods
DELETE delete
GET getForObject
getForEntity
HEAD headForHeaders
OPTIONS optionsForAllow
POST postForLocation
postForObject
PUT put
any exchange
execute

此外,exchange和excute可以通用上述方法。

在內(nèi)部,RestTemplate默認(rèn)使用HttpMessageConverter實(shí)例將HTTP消息轉(zhuǎn)換成POJO或者從POJO轉(zhuǎn)換成HTTP消息。默認(rèn)情況下會(huì)注冊(cè)主mime類型的轉(zhuǎn)換器,但也可以通過setMessageConverters注冊(cè)其他的轉(zhuǎn)換器。(其實(shí)這點(diǎn)在使用的時(shí)候是察覺不到的,很多方法有一個(gè)responseType 參數(shù),它讓你傳入一個(gè)響應(yīng)體所映射成的對(duì)象,然后底層用HttpMessageConverter將其做映射)

HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger);

HttpMessageConverter.java源碼:

public interface HttpMessageConverter<T> {
        //指示此轉(zhuǎn)換器是否可以讀取給定的類。
    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

        //指示此轉(zhuǎn)換器是否可以寫給定的類。
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

        //返回List<MediaType>
    List<MediaType> getSupportedMediaTypes();

        //讀取一個(gè)inputMessage
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException;

        //往output message寫一個(gè)Object
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException;

}

在內(nèi)部,RestTemplate默認(rèn)使用SimpleClientHttpRequestFactoryDefaultResponseErrorHandler來分別處理HTTP的創(chuàng)建和錯(cuò)誤,但也可以通過setRequestFactorysetErrorHandler來覆蓋。

2 get請(qǐng)求實(shí)踐

2.1 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()其實(shí)比getForEntity()多包含了將HTTP轉(zhuǎn)成POJO的功能,但是getForObject沒有處理response的能力。因?yàn)樗玫绞值木褪浅尚偷?code>pojo。省略了很多response的信息。

  • POJO
public class Notice {
    private int status;
    private Object msg;
    private List<DataBean> data;
}
public  class DataBean {
  private int noticeId;
  private String noticeTitle;
  private Object noticeImg;
  private long noticeCreateTime;
  private long noticeUpdateTime;
  private String noticeContent;
}
  • 示例:不帶參的get請(qǐng)求
/**
     * 不帶參的get請(qǐng)求
     */
@Test
public void restTemplateGetTest(){
    RestTemplate restTemplate = new RestTemplate();
    Notice notice = restTemplate
        .getForObject("http://xxx.top/notice/list/1/5", Notice.class);
    System.out.println(notice);
}

控制臺(tái)打?。?/p>

INFO 19076 --- [           main] c.w.s.c.w.c.HelloControllerTest          
: Started HelloControllerTest in 5.532 seconds (JVM running for 7.233)

Notice{status=200, msg=null, data=[DataBean{noticeId=21, noticeTitle='aaa', noticeImg=null, 
noticeCreateTime=1525292723000, noticeUpdateTime=1525292723000, noticeContent='<p>aaa</p>'}, 
DataBean{noticeId=20, noticeTitle='ahaha', noticeImg=null, noticeCreateTime=1525291492000, 
noticeUpdateTime=1525291492000, noticeContent='<p>ah.......'
  • 示例:帶參數(shù)的get請(qǐng)求1
Notice notice = restTemplate.
    getForObject("http://fantj.top/notice/list/{1}/{2}", Notice.class,1,5);

明眼人一眼能看出是用了占位符{1}。

  • 示例:帶參數(shù)的get請(qǐng)求2
 Map<String,String> map = new HashMap();
map.put("start","1");
map.put("page","5");
Notice notice = restTemplate
    .getForObject("http://fantj.top/notice/list/", Notice.class,map);

利用map裝載參數(shù),不過它默認(rèn)解析的是PathVariable的url形式。

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

與getForObject()方法不同的是返回的是ResponseEntity對(duì)象,如果需要轉(zhuǎn)換成pojo,還需要json工具類的引入,這個(gè)按個(gè)人喜好用。不會(huì)解析json的可以百度FastJson或者Jackson等工具類。然后我們就研究一下ResponseEntity下面有啥方法。

ResponseEntity、HttpStatus、BodyBuilder結(jié)構(gòu)

  • 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> {
    //設(shè)置正文的長(zhǎng)度,以字節(jié)為單位,由Content-Length標(biāo)頭
      BodyBuilder contentLength(long contentLength);
    //設(shè)置body的MediaType 類型
      BodyBuilder contentType(MediaType contentType);
    //設(shè)置響應(yīng)實(shí)體的主體并返回它。
      <T> ResponseEntity<T> body(@Nullable T body);
}

可以看出來,ResponseEntity包含了HttpStatus和BodyBuilder的這些信息,這更方便我們處理response原生的東西。

  • 示例
@Test
public void rtGetEntity(){
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Notice> entity =restTemplate
        .getForEntity("http://fantj.top/notice/list/1/5", Notice.class);

    HttpStatus statusCode = entity.getStatusCode();
    System.out.println("statusCode.is2xxSuccessful()"+statusCode.is2xxSuccessful());

    Notice body = entity.getBody();
    System.out.println("entity.getBody()"+body);

    ResponseEntity.BodyBuilder status = ResponseEntity.status(statusCode);
    status.contentLength(100);
    status.body("我在這里添加一句話");
    ResponseEntity<Class<Notice>> body1 = status.body(Notice.class);
    Class<Notice> body2 = body1.getBody();
    System.out.println("body1.toString()"+body1.toString());
}
statusCode.is2xxSuccessful()true
entity.getBody()Notice{status=200, msg=null, data=[DataBean{noticeId=21, noticeTitle='aaa', ...
body1.toString()<200 OK,class com.waylau.spring.cloud.weather.pojo.Notice,{Content-Length=[100]}>

3 post請(qǐng)求實(shí)踐

同樣的,post請(qǐng)求也有postForObjectpostForEntity。

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 {}
  • 示例

用一個(gè)驗(yàn)證郵箱的接口來測(cè)試。

@Test
public void rtPostObject(){
    RestTemplate restTemplate = new RestTemplate();
    String url = "http://47.xxx.xxx.96/register/checkEmail";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
    map.add("email", "844072586@qq.com");

    HttpEntity<MultiValueMap<String, String>> request 
        = new HttpEntity<>(map, headers);
    ResponseEntity<String> response 
        = restTemplate.postForEntity( url, request , String.class );
    System.out.println(response.getBody());
}

執(zhí)行結(jié)果:

{"status":500,"msg":"該郵箱已被注冊(cè)","data":null}

代碼中,MultiValueMapMap的一個(gè)子類,它的一個(gè)key可以存儲(chǔ)多個(gè)value,簡(jiǎn)單的看下這個(gè)接口:

public interface MultiValueMap<K, V> extends Map<K, List<V>> {...}

為什么用MultiValueMap?因?yàn)?code>HttpEntity接受的request類型是它。

public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers){}
我這里只展示它的一個(gè)construct,從它可以看到我們傳入的map是請(qǐng)求體,headers是請(qǐng)求頭。

為什么用HttpEntity?

是因?yàn)?code>restTemplate.postForEntity方法雖然表面上接收的request是@Nullable Object request類型,但是你追蹤下去會(huì)發(fā)現(xiàn),這個(gè)request是用HttpEntity來解析。

核心代碼如下:

if (requestBody instanceof HttpEntity) {
    this.requestEntity = (HttpEntity<?>) requestBody;
}else if (requestBody != null) {
    this.requestEntity = new HttpEntity<>(requestBody);
}else {
    this.requestEntity = HttpEntity.EMPTY;
}

我曾嘗試用map來傳遞參數(shù),編譯不會(huì)報(bào)錯(cuò),但是執(zhí)行不了,是無效的url request請(qǐng)求(400 ERROR)。其實(shí)這樣的請(qǐng)求方式已經(jīng)滿足post請(qǐng)求了,cookie也是屬于header的一部分??梢园葱枨笤O(shè)置請(qǐng)求頭和請(qǐng)求體。其它方法與之類似。

4 使用exchange指定調(diào)用方式

exchange()方法跟上面的getForObject()、getForEntity()、postForObject()、postForEntity()等方法不同之處在于它可以指定請(qǐng)求的HTTP類型。

但是你會(huì)發(fā)現(xiàn)exchange的方法中似乎都有@Nullable HttpEntity<?> requestEntity這個(gè)參數(shù),這就意味著我們至少要用HttpEntity來傳遞這個(gè)請(qǐng)求體,之前說過源碼所以建議就使用HttpEntity提高性能。

 @Test
public void rtExchangeTest() throws JSONException {
    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());
}

這次可以看到,我使用了JSONObject對(duì)象傳入和返回。

當(dāng)然,HttpMethod方法還有很多,用法類似。

5 excute()指定調(diào)用方式

excute()的用法與exchange()大同小異了,它同樣可以指定不同的HttpMethod,不同的是它返回的對(duì)象是響應(yīng)體所映射成的對(duì)象<T>,而不是ResponseEntity<T>。

需要強(qiáng)調(diào)的是,execute()方法是以上所有方法的底層調(diào)用。隨便看一個(gè):

@Override
@Nullable
public <T> T postForObject(String url, @Nullable Object request, 
                           Class<T> responseType, 
                           Map<String, ?> uriVariables)
    throws RestClientException {
    RequestCallback requestCallback 
        = httpEntityCallback(request, responseType);
    HttpMessageConverterExtractor<T> responseExtractor 
        = new HttpMessageConverterExtractor<>(responseType,
                        getMessageConverters(),logger);
    return execute(url, HttpMethod.POST,
                   requestCallback, 
                   responseExtractor, uriVariables);
}

6 小結(jié)

本篇文章講的是一個(gè)發(fā)送Http請(qǐng)求的方式——Spring的RestTemplate,由于純手打,難免會(huì)有紕漏,如果發(fā)現(xiàn)錯(cuò)誤的地方,請(qǐng)第一時(shí)間告訴我,這將是我進(jìn)步的一個(gè)很重要的環(huán)節(jié)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容