天天看點

SpringBoot-30-RestTemplate的Post詳解

作者:springboot葵花寶典

SpringBoot-30-RestTemplate的Post詳解

RestTemplate的Htttp Post請求我們經常使用下面兩個方法:

  • postForObject():傳回Http協定的響應體
  • postForEntity():傳回ResponseEntity,ResponseEntity對Http進行了封裝,除了包含響應體以外,還包含Http狀态碼、contentType、Header等資訊。

postForObject()方法的使用

發送Json格式

我們還是使用免費接口位址http://jsonplaceholder.typicode.com作為我們的測試資料位址,我們寫一個接口代碼如下,

@RequestMapping("/testpost")
@RestController
public class TestController {
    @Autowired
    private RestTemplate restTemplate;
    @PostMapping("comments")
    public TestEntity test(){
        TestEntity entity = new TestEntity();
        entity.setId(501);
        entity.setPostId(101);
        entity.setBody("test demo");
        entity.setEmail("[email protected]");
        entity.setName("zhouo bang");
        TestEntity forEntity = restTemplate.postForObject("http://jsonplaceholder.typicode.com/comments?author.name=typicode", entity,TestEntity.class);
        return forEntity;
    }
}
           

TestEntity實體類

@Data
public class TestEntity {
    private int postId;
    private int id;
    private String name;
    private String email;
    private String body;
}
           

測試http://localhost:8080/testpost/comments接口,結果為:

SpringBoot-30-RestTemplate的Post詳解

注:postForObject的第二個參數是請求資料對象,第三個參數是傳回值類型。

表單資料送出

postForObject模拟表單資料送出的例子,代碼如下

  @PostMapping("comments/form")
    public String testform(){
        // 請求位址
        String url = "http://jsonplaceholder.typicode.com/comments";
        // 請求頭設定,x-www-form-urlencoded格式的資料
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //送出參數設定
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("postId", "102");
        map.add("id", "502");
        map.add("name", "li si");
        map.add("email", "[email protected]");
        map.add("body", "my body");
        // 組裝請求體
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(map, headers);
        // 發送post請求,并列印結果,以String類型接收響應結果JSON字元串
        String result = restTemplate.postForObject(url, request, String.class);
        return result;
    }
           

使用Postman測試http://localhost:8080/testpost/comments/form結果如下

SpringBoot-30-RestTemplate的Post詳解

使用占位符傳遞參數

  • 使用占位符的形式傳遞參數http://jsonplaceholder.typicode.com/{1}
    @PostMapping("comments_1/{type}")
    public TestEntity test_1(@PathVariable("type")String type){
        TestEntity entity = new TestEntity();
        entity.setId(501);
        entity.setPostId(101);
        entity.setBody("test demo");
        entity.setEmail("[email protected]");
        entity.setName("zhouo bang");
        TestEntity forEntity = restTemplate.postForObject("http://jsonplaceholder.typicode.com/{1}", entity,TestEntity.class,type);
        return forEntity;
    }
           
  • 另一種形式傳參http://jsonplaceholder.typicode.com/{type}
    @PostMapping("comments_2/{type}")
    public TestEntity test_2(@PathVariable("type")String type){
        TestEntity entity = new TestEntity();
        entity.setId(501);
        entity.setPostId(101);
        entity.setBody("test demo");
        entity.setEmail("[email protected]");
        entity.setName("zhouo bang");
        TestEntity forEntity = restTemplate.postForObject("http://jsonplaceholder.typicode.com/{type}", entity,TestEntity.class,type);
        return forEntity;
    }
           
  • 使用 map 裝載參數
    @PostMapping("comments_3/{type}")
    public TestEntity test_3(@PathVariable("type")String type){
        TestEntity entity = new TestEntity();
        entity.setId(501);
        entity.setPostId(101);
        entity.setBody("test demo");
        entity.setEmail("[email protected]");
        entity.setName("zhouo bang");
        Map<String,Object> map = new HashMap<>();
        map.put("type",type);
        TestEntity forEntity = restTemplate.postForObject("http://jsonplaceholder.typicode.com/{type}", entity,TestEntity.class,map);
        return forEntity;
    }
           

postForEntity()方法的使用

getForObject()所有的傳參請求方式,getForEntity()都可以使用,使用方式也幾乎一樣。在傳回結果上有差別,使用**ResponseEntity**來就收響應結果。

    @PostMapping("comments_4/{type}")
    public TestEntity test_4(@PathVariable("type")String type){
        TestEntity entity = new TestEntity();
        entity.setId(520);
        entity.setPostId(110);
        entity.setBody("comments_4 demo");
        entity.setEmail("[email protected]");
        entity.setName("zhouo comments_4");
        Map<String,Object> map = new HashMap<>();
        map.put("type",type);
        ResponseEntity<TestEntity> forEntity = restTemplate.postForEntity("http://jsonplaceholder.typicode.com/{type}", entity,TestEntity.class,map);
        System.out.println("StatusCode: "+ forEntity.getStatusCode());
        System.out.println("StatusCodeValue: "+forEntity.getStatusCodeValue());
        System.out.println("Headers: "+ forEntity.getHeaders());
        return forEntity.getBody();
    }
           

測試傳回結果會和上面的一樣,但是在console會有輸出

SpringBoot-30-RestTemplate的Post詳解
SpringBoot-30-RestTemplate的Post詳解

postForLocation() 方法的使用

postForLocation用法基本都和postForObject()或postForEntity()一緻。唯一差別在于傳回值是一個URI。該URI傳回值展現的是:用于送出完成資料之後的頁面跳轉,或資料送出完成之後的下一步資料操作URI。

@PostMapping("comments_5/{type}")
public String test_5(@PathVariable("type")String type){
    TestEntity entity = new TestEntity();
    entity.setId(520);
    entity.setPostId(110);
    entity.setBody("comments_4 demo");
    entity.setEmail("[email protected]");
    entity.setName("zhouo comments_4");
    Map<String,Object> map = new HashMap<>();
    map.put("type",type);
    URI uri = restTemplate.postForLocation("http://jsonplaceholder.typicode.com/{type}",entity,map);
    return uri.getPath();
}
           

使用postman 測試http://localhost:8080/testpost/comments_5/comments

SpringBoot-30-RestTemplate的Post詳解

傳回結果為

"http://jsonplaceholder.typicode.com/comments/501"