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();

post请求
RestTemplate restTemplate= new RestTemplate();
WorkSheetGroupRequest request = new WorkSheetGroupRequest();
request.setGroupName("ggg");
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "503392be09ed4ed582cf3e92916dc22e");
headers.add("Content-Type", "application/json");

HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(request), headers);
String url = "http://10.133.232.41:8081/zjk/workSheet/group/save";
ResponseEntity<Void> responseEntity = restTemplate.exchange(url,
HttpMethod.POST, httpEntity, Void.class);

 

 

 

第二种: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}"); }
posted @ 2019-06-24 16:49  高木子  阅读(4023)  评论(0编辑  收藏  举报