Springboot与RestTemplate

发布于:2024-06-22 ⋅ 阅读:(119) ⋅ 点赞:(0)

        RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

一、使用Get进行访问

1、获取json格式

        使用 getForEntity() API 发起 GET 请求:

RestTemplate restTemplate = new RestTemplate();
        String fooResourceUrl = "http://localhost:8080/spring-rest/foos";
        ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
        System.out.println(response.getStatusCode());

        可以访问完整的 HTTP 响应,因此可以检查 HTTP 状态码是否成功,或者处理响应体:

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(response.getBody());
JsonNode name = root.path("name");
System.out.println(name.asText());

        如上,将响应体作为标准字符串(String)返回,并使用 Jackson(以及 Jackson 提供的 JSON 节点结构)来验证一些细节。

2、获取pojo格式

        可以将响应直接映射到资源 DTO:

public class Foo implements Serializable {
    private long id;

    private String name;
    // 标准的 get 、set 方法
}

        只需要调用 template 的 getForObject API 即可:

Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
Assertions.assertNotNull(foo.getName());
Assertions.assertEquals(foo.getId(), 1L);

二、使用Post进行访问

1、传递表单参数

        可以使用 postForLocation()postForObject() 或 postForEntity() 方法 在 API 中创建新资源。前者(postForLocation)返回新创建资源的 URI,后者返回资源本身。

    // 创建请求头对象
        HttpHeaders headers = new HttpHeaders();
        // 设置请求内容类型 表单上传编码格式为application/x-www-form-urlencoded
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 请求携带的参数与对应的值
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username", USER_NAME);
        map.add("password", PASSWORD);
        // HttpEntity表示http的request和resposne实体,它由消息头和消息体组成。
        // 从HttpEntity中可以获取http请求头和回应头,也可以获取http请求体和回应体信息。
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        return restTemplate.postForObject(TOKEN_URL, request, ComplainWorkToken.class);

2、传递json参数

        HttpHeaders headers = new HttpHeaders();
        // 设置请求头是json
        headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        // 携带的json参数格式
        Map<String, Object> map2 = new HashMap<>();
        map2.put("pageNo", pageNo);
        map2.put("pageSize", pageSize);
        map2.put("endTime", endTime);
        map2.put("startTime", startTime);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map2, headers);
        ComplainWorkResponse complainWorkResponse = restTemplate.postForObject(url, httpEntity, ComplainWorkResponse.class);
        assert complainWorkResponse != null;
        return complainWorkResponse.getComplainWorkData().getList();

网站公告

今日签到

点亮在社区的每一天
去签到