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()))); } });