码迷,mamicode.com
首页 > 其他好文 > 详细

RestTemplate之GET和POST调用和异步回调

时间:2018-07-21 17:10:47      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:.post   error   void   bsp   pre   type   device   cep   ams   

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调用和异步回调

标签:.post   error   void   bsp   pre   type   device   cep   ams   

原文地址:https://www.cnblogs.com/zhangpengshou/p/9346349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!