SpringBoot-30-RestTemplate的Post详解

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("Davion@zz.net");
        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接口,结果为:

: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", "qq.@qq.com");
        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结果如下

使用占位符传递参数

  • 使用占位符的形式传递参数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("Davion@zz.net");
        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("Davion@zz.net");
        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("Davion@zz.net");
        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("comments_4@zz.net");
        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会有输出

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("comments_4@zz.net");
    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

返回结果为

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值