Spring Boot之發送HTTP請求(RestTemplate詳解)


原文作者:微笑面對生活

https://www.javazhiyin.com/19714.html#comment-345

 

RestTemplate是Spring提供的用於訪問Rest服務的客戶端,RestTemplate提供了多種便捷訪問遠程Http服務的方法

1.簡述RestTemplate

RestTemplate能大幅簡化了提交表單數據的難度,並且附帶了自動轉換JSON數據的功能

HTTP方式 RestTemplate方法
GET

getForObject()

getForEntity()

POST

postForLocation()

postForObject()

PUT

put

DELETE

delete

 

 

 

 

 

 

 

 

 

在內部,RestTemplate默認使用HttpMessageConverter實例將HTTP消息轉換成POJO或者從POJO轉換成HTTP消息。

默認情況下會注冊主mime類型的轉換器,但也可以通過setMessageConverters注冊其他的轉換器。

 

在內部,RestTemplate默認使用SimpleClientHttpRequestFactory和DefaultResponseErrorHandler來分別處理HTTP的創建和錯誤,但也可以通過setRequestFactory和setErrorHandler來覆蓋。

2.get請求實踐(我們在java后台的HTTP發送中最最常用的就是GET請求了

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()其實比getForEntity()多包含了將HTTP轉成POJO的功能,但是getForObject沒有處理response的能力。因為它拿到手的就是成型的pojo。省略了很多response的信息。

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;
}

示例:2.1.2 不帶參的get請求

/**
     * 不帶參的get請求
     */
    @Test
    public void restTemplateGetTest(){
        try {
            RestTemplate restTemplate = new RestTemplate();
       //將指定的url返回的參數自動封裝到自定義好的對應類對象中 Notice notice
= restTemplate.getForObject("http://xxx.top/notice/list/1/5",Notice.class); System.out.println(notice); }catch (HttpClientErrorException e){ System.out.println("http客戶端請求出錯了!"); //開發中可以使用統一異常處理,或者在業務邏輯的catch中作響應 } }

控制台打印:

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.......'

  

示例:2.1.3 帶參數的get請求1

Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}", Notice.class,1,5);

上面使用了占位符,將1和5作為參數傳入的請求URL中的第一個參數{1}處和第二個參數{2}處

示例:2.1.4 帶參數的get請求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裝載參數,不過它默認解析的是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()方法不同的是,getForEntity()方法返回的是ResponseEntity對象,如果需要轉換成pojo,還需要json工具類的引入。可以引入FastJson等工具類解析json。

然后我們就研究一下ResponseEntity下面有啥方法。

ResponseEntity、HttpStatus、BodyBuilder結構

 

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);
    //設置響應實體的主體並返回它。
      <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]}>

 

 

同樣的,post請求也有postForObject和postForEntity。

3. post請求實踐

 同樣的,post請求也有postForObject和postForEntity。

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 {}
 
示例 
我用一個驗證郵箱的接口來測試。
@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());
}

執行結果:

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

 

更多請看:

https://www.javazhiyin.com/19714.html#comment-345

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM