首页  编辑  

用Map包装的请求参数如何用RestTemplate 实现 HTTP GET

Tags: /Java/   Date Created:
我们可能用Map<String, Object>封装请求参数列表,那么如何把这个Map转为RestTemplate进行HTTP GET请求呢?
代码:
    RestTemplate restTemplate = new RestTemplate();
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
    condition.forEach(uriBuilder::queryParam);
    URI uri = uriBuilder.build().encode().toUri();
    RequestEntity<Void> requestEntity = new RequestEntity<>(HttpMethod.GET, uri);
    ResponseEntity<JSONObject> response = restTemplate.exchange(requestEntity, JSONObject.class);
或者:
URI uri = UriComponentsBuilder.fromHttpUrl(url).buildAndExpand(condition).encode().toUri();
RestTemplate restTemplate = new RestTemplate();
JSONObject response = restTemplate.getForObject(uri, JSONObject.class);