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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM