1. 程式人生 > >Spring restTemplate使用

Spring restTemplate使用

最近看到spring RestTemplate,覺得挺好用的,就研究總結了一下,第一次寫。。。 
RestTemplate可使用http的所有方式進行請求,本文主要說明下get,post的使用,其他的基本類似。

http get 方式

spring RestTemplate中直接使用get方法有兩種getForObject和getForEntity

getForObject

每種方式都有3個過載方法

  1. T getForObject(URI url, Class responseType)
  2. T getForObject(String url, Class responseType, MapString< String, ?> urlVariables)
  3. T getForObject(String url, Class responseType, Object… urlVariables) 
    其中url為請求url,可用萬用字元表示請求引數,responseType為請求返回的物件類,自動封裝成物件該物件形式, Map< String, ?> urlVariables表示請求引數,與萬用字元對應即可, Object… urlVariables為請求的引數陣列形式,按順序一一匹配url中內容,例子如下: 
    User 類,省略get,set方法
public class User {

    private String name;

    private
Integer age;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
private RestTemplate restTemplate = new RestTemplate();

    private String name = "xiaoming";

    private Integer age = 18;
  • 1
  • 2
  • 3
  • 4
  • 5

getForObject 
傳送方

String url = "http://localhost:8080/getUser?name={name}&age={age}";
        Object[] arr = new Object[]{name, age};
        User u = restTemplate.getForObject(url, User.class, arr);
  • 1
  • 2
  • 3

    String url = "http://localhost:8080/getUser?name={name}&age={age}";
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("age", age);
        User u = restTemplate.getForObject(url, User.class, map);
  • 1
  • 2
  • 3
  • 4
  • 5

接收方

public User get1(@RequestParam String name, @RequestParam Integer age)
  • 1

getForEntity

getForEntity與getForObject請求引數基本一樣,只是返回內容不一樣 
ResponseEntity getForEntity(String url, Class responseType, Object… urlVariables) 
getForEntity返回ResponseEntity,裡面包含返回訊息內容和http headers,http 狀態碼,如下例

String url = "http://localhost:8080/getUser?name={name}&age={age}";
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("age", age);
        ResponseEntity<User> res = restTemplate.getForEntity(url, User.class, map);
        User u = res.getBody();
        HttpHeaders headers = res.getHeaders();
        HttpStatus status = res.getStatusCode();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

以上是RestTemplate的get請求使用方式,對於get請求傳送head資訊的,實現在下面說到

http post 方式

post方法主要有3種方法:postForObject, postForEntity和postForLocation

postForObject

同樣有3種過載

  1. T postForObject(String url, Object request, Class responseType, Object… uriVariables)
  2. T postForObject(String url, Object request, Class responseType, Map
private HttpEntityRequestCallback(Object requestBody, Type responseType) {
            super(responseType);
            if (requestBody instanceof HttpEntity) {
                this.requestEntity = (HttpEntity<?>) requestBody;
            }
            else if (requestBody != null) {
                this.requestEntity = new HttpEntity<Object>(requestBody);
            }
            else {
                this.requestEntity = HttpEntity.EMPTY;
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

可以看到Object request最終都會轉換為HttpEntity,httpEntity類中如下

public class HttpEntity<T> {

    /**
     * The empty {@code HttpEntity}, with no body or headers.
     */
    public static final HttpEntity<?> EMPTY = new HttpEntity<Object>();


    private final HttpHeaders headers;

    private final T body;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

主要包含headers和body兩部分內容,如果Object request可直接轉為HttpEntity,則可直接使用,否則預設為HttpEntity中body的內容 
引數傳遞,這種post方式可以避開get方法引數過長的影響,不限制引數長度

String url = "http://localhost:8080/getUser";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("name", name);
        map.add("age", age);

        User u = restTemplate.postForObject(url, map, User.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

String url = "http://localhost:8080/getUser";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("name", name);
        map.add("age", age);

        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map);

        User u = restTemplate.postForObject(url, httpEntity, User.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

接收方

 public User get1(@ModelAttribute User user)
  • 1

傳遞http head資訊,可自行設定http請求的head資訊 
傳送方

String url = "http://localhost:8080/getUser";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("name", name);
        map.add("age", age);

        HttpHeaders headers = new HttpHeaders();
        headers.add("msg", "head msg test");    

        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);

        User u = restTemplate.postForObject(url, httpEntity, User.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

接收方

@RequestMapping(value = "/getUser", method = {RequestMethod.POST})
    public User get1(@RequestParam String name, @RequestParam Integer age, @RequestHeader(required = false)  String msg)
  • 1
  • 2

postForEntity和postForLocation

postForEntity返回ResponseEntity,與getForEntity相同 
postForLocation返回URI,返回的是response header中的location資訊,一般用於資源定位。

exchange方法

spring直接提供了所有http的請求的公用方法exchange,簡單介紹下

ResponseEntity exchange(String url, HttpMethod method, 
HttpEntity< ?> requestEntity, Class responseType, Object… uriVariables) 
引數設定基本相同,多了個HttpMethod ,設定http的請求方式,通過這個就可以設定Http Get方式的頭資訊