restTemplate系列-exchange

exchange

提示:exchange使用举例

前言

restTemplate的get和post使用的比较多,那么更为通用的exchange怎么使用呢。


代码如下(示例):
exchange

// 1.3 get请求返回List<T>类型
@GetMapping("/user/list")
public List<UserDto> getUserList(@RequestParam("name") String name) {
    String url = "http://localhost:8080/demo/user/list/mock?name=" + name;
    ParameterizedTypeReference<List<UserDto>> responseBodyType = new ParameterizedTypeReference<List<UserDto>>() {};
    return restTemplate.exchange(url, HttpMethod.GET, null, responseBodyType).getBody();
}
// 1.4 get请求返回Map类型
@GetMapping("/user/map")
public Map<String, Object> getUserMap(@RequestParam(value = "type", required = true) Integer type, @RequestParam("key") String key) {
    String url = "http://localhost:8080/demo/user/map/mock?type=" + type + "&key=" + key;
    ParameterizedTypeReference<Map<String, Object>> responseBodyType = new ParameterizedTypeReference<Map<String, Object>>() {};
    return restTemplate.exchange(url, HttpMethod.GET, null, responseBodyType).getBody();
}
// 1.5 get请求返回自定义泛型类型
@GetMapping("/user/result")
public Result<UserDto> getUserResult(@RequestParam("id") Integer id) {
    String url = "http://localhost:8080/demo/user/result/mock?id=" + id;
    ParameterizedTypeReference<Result<UserDto>> responseBodyType = new ParameterizedTypeReference<Result<UserDto>>() {};
    return restTemplate.exchange(url, HttpMethod.GET, null, responseBodyType).getBody();
}
@GetMapping("/user/body")
public UserDto postUser(@RequestParam("id") Integer id) {
    String url = "http://localhost:8080/demo/user/body/mock";
    UserDto body = UserDto.builder().id(id)
            .name("body" + id)
            .age(id + 18)
            .birthday(new Date()).build();
    // header根据实际情况设置,没有就空着
    HttpHeaders headers = new HttpHeaders();
    headers.add("AccessKey", "自定义的API访问key");
    headers.add("Content-Type", "application/json");
    HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
    return restTemplate.exchange(url, HttpMethod.POST, requestEntity, UserDto.class).getBody();
}
@GetMapping("/user/result/body")
public Result<UserDto> postUserResult(@RequestParam("id") Integer id) {
    String url = "http://localhost:8080/demo/user/result/body/mock";
    UserDto body = UserDto.builder().id(id)
            .name("body" + id)
            .age(id + 10)
            .birthday(new Date()).build();
    // header根据实际情况设置,没有就空着
    HttpHeaders headers = new HttpHeaders();
    headers.add("AccessKey", "自定义的API访问key");
    headers.add("Content-Type", "application/json");
    HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
    ParameterizedTypeReference<Result<UserDto>> responseBodyType = new ParameterizedTypeReference<Result<UserDto>>(){};
    return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseBodyType).getBody();
}

public static void main(String[] args) {
        RestTemplate restTemplate2 = new RestTemplate();
        String url = "http://127.0.0.1:8081/interact/getData?dt={dt}&ht={ht}";
   
        // 封装参数,这里是HashMap
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("dt", "20181116");
    paramMap.put("ht", "10");
 
    //1、使用getForObject请求接口
    String result1 = template.getForObject(url, String.class, paramMap);
    System.out.println("result1====================" + result1);
 
    //2、使用exchange请求接口
    HttpHeaders headers = new HttpHeaders();
    headers.set("id", "lidy");
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
    ResponseEntity<String> response2 = template.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);
    System.out.println("result2====================" + response2.getBody());
}

public <T> T exchangeForEntity(HttpMethod httpMethod, String url, HttpHeaders headers, Object body
			, Class<T> responseType) {
    HttpEntity<?> requestEntity = null;
    if (headers != null || body != null) {
        requestEntity = new HttpEntity<>(body, headers);
    }
    try {
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, responseType);
        if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
            return responseEntity.getBody();
        } else {
            // 处理Code不等于200的情况, 这里只简单打印,你需要根据你们项目的情况修改合适的处理方式
            System.out.println("返回结果不等于200:code=" + responseEntity.getStatusCode().value()
                    + " reason=" + responseEntity.getStatusCode().getReasonPhrase());
        }
    } catch (RestClientException e) {
        // 处理RestClientException
        e.printStackTrace();
    }
    return null;
}

  • 泛型类型:
    `只需要将普通类型的入参Class改成 ParameterizedTypeReference
public static void main(String[] args) {
        RestTemplate template = new RestTemplate();
        String url = "http://192.168.2.40:8081/channel/channelHourData/getHourNewUserData";
        // 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("dt", "20180416");
 
        // 1、使用postForObject请求接口
        String result = template.postForObject(url, paramMap, String.class);
        System.out.println("result1==================" + result);
 
        // 2、使用postForEntity请求接口
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
        System.out.println("result2====================" + response2.getBody());
 
        // 3、使用exchange请求接口
        ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
        System.out.println("result3====================" + response3.getBody());
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值