restTemplate 发送get,post请求,占位符传参

RestTemplate可以发送HTTP 请求,经常使用到的方法有两个:

getForObject()

getForEntity()

二者的主要区别在于,getForObject()返回值是HTTP协议的响应体。getForEntity()返回的是ResponseEntity,ResponseEntity是对HTTP响应的封装,除了包含响应体,还包含HTTP状态码、contentType、contentLength、Header等信息。

restTemplate 发送get 不带参数



    @Operation( summary= "保存数据", description = "保存数据")
    @GetMapping(value = "/addTasks1")
    public ReturnModel<Integer> addTasks1() throws IOException {

        String url = "http://127.0.0.1:8080/api/task/test";
        Map<String, Object> params = new HashMap<>();
        params.put("name", "这是name");
        params.put("id", 1L);
        ResponseEntity<ResultModel> forEntity = restTemplate.getForEntity(url, ResultModel.class);
        //String rm = forEntity.getBody();

        //ObjectMapper mapper = new ObjectMapper();
        //ReturnModel rmObj  = mapper.readValue(rm, ReturnModel.class);
        return null;
    }

@Test
public void testArrays() {
   String url = "http://jsonplaceholder.typicode.com/posts";
   PostDTO[] postDTOs = restTemplate.getForObject(url, PostDTO[].class);
   System.out.println("数组长度:" + postDTOs.length);
}
@Test
public void testPoJO() {
   String url = "http://jsonplaceholder.typicode.com/posts/1";
   PostDTO postDTO = restTemplate.getForObject(url, PostDTO.class);
   System.out.println(postDTO.toString());
}

restTemplate 发送post不带参数

@Operation( summary= "保存数据", description = "保存数据")
    @GetMapping(value = "/addTasks2")
    public ReturnModel<Integer> addTasks2() throws IOException {

        String url = "http://127.0.0.1:8080/api/task/test";
        Map<String, Object> params = new HashMap<>();
        params.put("name", "这是name");
        params.put("id", 1L);
        ResponseEntity<ResultModel> responseEntity = restTemplate.postForEntity(url, params, ResultModel.class);

        // ResponseEntity<ResultModel> forEntity = restTemplate.getForEntity(url, ResultModel.class);
        //String rm = forEntity.getBody();

        //ObjectMapper mapper = new ObjectMapper();
        //ReturnModel rmObj  = mapper.readValue(rm, ReturnModel.class);
        return null;
    }

restTemplate 发送post 带参数

@Operation( summary= "保存数据", description = "保存数据")
    @GetMapping(value = "/addTasks")
    public ReturnModel<Integer> addTasks() throws IOException {

        String url = "http://127.0.0.1:8080/api/task/addTasks";
        List<TaskDto> list = new ArrayList<>();
        list.add(TaskDto.builder().businessId("测试").employeeCode("110").taskId(778L).isCompleted("0").personalName("张三").genTime(LocalDateTime.now()).build());
        list.add(TaskDto.builder().businessId("测试1").employeeCode("110").taskId(779L).isCompleted("0").personalName("张三1").genTime(LocalDateTime.now()).build());
        list.add(TaskDto.builder().businessId("测试2").employeeCode("110").taskId(780L).isCompleted("0").personalName("张三2").genTime(LocalDateTime.now()).build());

        TaskSaveDto wlk = TaskSaveDto.builder().taskList(list).systemCode("WLK").build();

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<TaskSaveDto> entity = new HttpEntity<TaskSaveDto>(wlk, headers);
        ResponseEntity<ResultModel> responseEntity = restTemplate.postForEntity(url, entity, ResultModel.class);

        ResultModel body = responseEntity.getBody();
        log.info(body.toString());
        // ResponseEntity<ResultModel> forEntity = restTemplate.getForEntity(url, ResultModel.class);
        //String rm = forEntity.getBody();

        //ObjectMapper mapper = new ObjectMapper();
        //ReturnModel rmObj  = mapper.readValue(rm, ReturnModel.class);
        return null;
    }
private HttpHeaders setHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Accept-Charset", "UTF-8");
        return headers;
    }

占位符传参

以下的几个请求都是在访问"http://baidu.com/posts/1",只是使用了占位符语法,这样在业务使用上更加灵活。

使用占位符的形式传递参数:

String url = “http://jsonplaceholder.typicode.com/{1}/{2}”;
PostDTO postDTO = restTemplate.getForObject(url, PostDTO.class, “posts”, 1);
另一种使用占位符的形式:

String url = “http://jsonplaceholder.typicode.com/{type}/{id}”;
String type = “posts”;
int id = 1;
PostDTO postDTO = restTemplate.getForObject(url, PostDTO.class, type, id);
我们也可以使用 map 装载参数:

String url = “http://jsonplaceholder.typicode.com/{type}/{id}”;
Map<String,Object> map = new HashMap<>();
map.put(“type”, “posts”);
map.put(“id”, 1);
PostDTO postDTO = restTemplate.getForObject(url, PostDTO.class, map);

getForEntity() getForObjec方法

getForObject请求传参方法,getForEntity都可以使用,使用方法上也几乎是一致的,只是在返回结果接收的时候略有差别。使用ResponseEntity responseEntity来接收响应结果。用responseEntity.getBody()获取响应体。响应体内容同getForObject方法返回结果一致。剩下的这些响应信息就是getForEntity比getForObject多出来的内容。

HttpStatus statusCode = responseEntity.getStatusCode();获取整体的响应状态信息

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值