zoukankan      html  css  js  c++  java
  • Spring 调用rest http接口的两种方式RestTemplate和WebClient

    第一种:spring的RestTemplate

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    //header
    headers.set("Authorization", "1172452ae5f144cda26790d2ad18118e");
    //MultiValueMap<String, String> params= new LinkedMultiValueMap<>(); //application/x-www-form- urlencoded
    Map<String, Object> map  = Maps.newHashMap();
    //参数
    map.add("","");
    map.add("","");
    HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(map, headers);
    //HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
    ResponseEntity<String> response = restTemplate.exchange("http://localhost:9000/supplywater/workSheet/getPageGroup", HttpMethod.GET, requestEntity, String.class);
    String sttr = response.getBody();

    第二种:Spring WebFlux 5.0版本开始提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具WebClient

    get请求

            Flux<Map> resp = WebClient.create("http://localhost:9000")
                    .get()
                    .uri("/supplywater/workSheet/getPageGroup")
                    .header("Authorization", "a42529f1532d4f9a9aac9fc080198c24")
                    .retrieve()
                    .bodyToFlux(Map.class);
            List<Map> block = resp.collectList().block();
            System.err.println(block);

     post请求

    Map<String, Object> map  = Maps.newHashMap();
    map.put("houseId",2458877830751060992L);
    map.put("date","2020");
    Mono<String> resp = WebClient.create()
    .method(HttpMethod.POST)
    .uri(url).header("Authorization", "4217c842edfa4283adc7a0339c532118")
    .contentType(MediaType.APPLICATION_JSON_UTF8)
    .body(Mono.just(map), Map.class)
    .retrieve()
    .bodyToMono(String.class);
    String block = resp.block();
    /*Flux<String> res = WebClient.create()
    .method()
    .uri(url + wsProperties.getDevPath())
    .contentType(MediaType.APPLICATION_JSON_UTF8)
    .body(Mono.just(copy), String.class)
    .retrieve()
    .bodyToFlux(String.class);*/
    //res.collectList().block();
    调用(记得加@RequestBody 不然后会接收不到参数) @PostMapping(ModuleWaterConstant.MAPPING_PREFIX + "/http/dev/One") public ChiticResponse exportDevData(@RequestBody String request) { System.err.println(request+"%$$$$$$$$$$$$$$$$$$"); return ChiticResponse.success("{"sn":"FAF杭州","unitId":444444444545,"door":12,"ph":5.5}"); }
  • 相关阅读:
    linux动态库(.so)和静态库(.a)的区别
    LeetCode刷题笔记和想法(C++)
    tf-idf、朴素贝叶斯的短文本分类简述
    计算机操作系统(第三版)读书笔记
    react hook封装一个排序按钮,有效果图
    react使用fetch封装请求的方法-简单易懂
    react开发企业中后台产品、政务门户网站的一些总结
    git常见命令以及基本使用
    Linux系统下fd分配的方法
    netfilter-IPv4实现框架分析(一)
  • 原文地址:https://www.cnblogs.com/gaomanito/p/11078000.html
Copyright © 2011-2022 走看看