RestTemplate之GET和POST调用和异步回调
Posted zhangpengshou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RestTemplate之GET和POST调用和异步回调相关的知识,希望对你有一定的参考价值。
get方式
String url = "http://hostname:port/v1.0/data/data"; HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("deviceSn", sensorAtom.getDeviceSn()) .queryParam("sensorSn", sensorAtom.getSensorSn()) .queryParam("metaData", metaData) .queryParam("apiKey", "abdb3876-9abb-4644-91c2-8fb3d33530bd"); HttpEntity<?> entity = new HttpEntity<>(headers); ListenableFuture<ResponseEntity<Response>> forEntity = asyncTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, Response.class); forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<Response>>() { @Override public void onFailure(Throwable ex) { logger.error(String.format("回调GET请求 %s 失败,%s", url, ex.getMessage())); } @Override public void onSuccess(ResponseEntity<Response> result) { logger.info(String.format("回调GET请求 %s 成功,返回值为%s", url, result.getBody())); } });
post方式
String url = "http://hostname:port/v1.0/data/report"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("deviceSn", sensorAtom.getDeviceSn()); params.add("sensorSn", sensorAtom.getSensorSn()); params.add("metaData", metaData); params.add("apiKey", "abdb3876-9abb-4644-91c2-8fb3d33530bd"); HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(params, headers); ListenableFuture<ResponseEntity<Response>> forEntity = asyncTemplate.postForEntity(url, requestEntity, Response.class); forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<Response>>() { @Override public void onFailure(Throwable ex) { logger.error(String.format("POST回调 %s 参数为 %s 请求失败,%s", url, JSON.toJSONString(params), ex.getMessage())); } @Override public void onSuccess(ResponseEntity<Response> result) { logger.info(String.format("POST回调 %s 参数为 %s 请求成功,返回值为 %s", url, JSON.toJSONString(params), JSON.toJSONString(result.getBody()))); } });
以上是关于RestTemplate之GET和POST调用和异步回调的主要内容,如果未能解决你的问题,请参考以下文章
springboot中使用restTemplate发送带参数和请求头的post,get请求
Spring RestTemplate用法 Post Get Cookie
如何使用带有Json主体和标头的RestTemplate进行POST调用? [重复]