• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
liuec1002
帮助1

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://百度.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();获取整体的响应状态信息

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgegbib
系列文章
更多 icon
同类精品
更多 icon
继续加载