zoukankan      html  css  js  c++  java
  • 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())));
        }
    });
  • 相关阅读:
    Comet OJ
    LOJ#2719. 「NOI2018」冒泡排序 DP+组合+树状数组
    LuoguP6747 『MdOI R3』Teleport 二进制+贪心
    LuoguP6748 『MdOI R3』Fallen Lord 树形DP+set
    LuoguP5576 [CmdOI2019]口头禅 后缀树+线段树+暴力
    LOJ#3161. 「NOI2019」I 君的探险 整体二分+随机化+二进制分组
    LOJ#2085. 「NOI2016」循环之美 莫比乌斯反演+杜教筛
    LuoguP5327 [ZJOI2019]语言 线段树合并+树链求并
    【考试题
    ELK
  • 原文地址:https://www.cnblogs.com/zhangpengshou/p/9346349.html
Copyright © 2011-2022 走看看