• 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}"); }
  • 相关阅读:
    刷面经笔记2019.02.11
    刷面经笔记2019.02.10
    刷面经笔记2019.02.09
    刷面经笔记2019.02.07
    刷面经笔记2019.02.05
    刷面经笔记2019.01.31
    刷面经笔记2019.01.30
    刷面经笔记2019.01.28
    头条2020届实习生笔试题
    金s办公软件web前端笔试题
  • 原文地址:https://www.cnblogs.com/gaomanito/p/11078000.html
Copyright © 2020-2023  润新知