RestTemplate调用第三方接口get/post请求

亲测可用!!!!

GET方式请求第三方接口

 RestTemplate REST_TEMPLATE = new RestTemplate(); 
 HttpHeaders httpHeaders = new HttpHeaders();
 Map paramMap= new HashMap<>(2);
 paramMap.put("username", test);
 paramMap.put("password", 123456);
 httpHeaders.setContentType(MediaType.APPLICATION_JSON);
 HttpEntity> httpEntity = new HttpEntity>(paramMap, httpHeaders);
 ResponseEntity response = REST_TEMPLATE.exchange("http://localhost:8081/data_service", HttpMethod.POST, httpEntity, String.class);
 JSONObject jsonObject = JSONObject.parseObject(response.getBody());

POST方式请求第三方接口

RestTemplate REST_TEMPLATE = new RestTemplate();
HttpHeaders httpHeader = new HttpHeaders();
httpHeader.add("Authorization", "Bearer 这是一个token");
Map paramMaps = new HashMap<>(3);
paramMaps.put("username", "cat");
paramMaps.put("age", 20);
HttpEntity> httpEntitys = new HttpEntity>(httpHeader);
ResponseEntity responseEntity = REST_TEMPLATE.exchange("http://localhost:8081/getUserInfo?username={username}&age={age}", HttpMethod.GET, httpEntitys, String.class,paramMaps);
JSONObject jsonObjects = JSONObject.parseObject(responseEntity.getBody());

你可能感兴趣的:(SpringBoot,idea,resttemplate,java)