private static ResponseEntity<String> getStringResponseEntity(String url, String method, Map<String, String> header, String body) throws JsonProcessingException {
HttpHeaders httpHeaders = new HttpHeaders();
header.forEach((a, b) -> httpHeaders.add(a, b));
HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
httpEntity = new HttpEntity<>(body, httpHeaders);
if (StringUtils.isBlank(body)) {
//GET
httpEntity = new HttpEntity<>(httpHeaders);
}
ResponseEntity<String> getResult = restTemplate.exchange(URI.create(url), HttpMethod.resolve(method), httpEntity, String.class);
return getResult;
}
static ObjectMapper objectMapper = new ObjectMapper();
static RestTemplate restTemplate = new RestTemplate();
public static void main(String[] args) throws JsonProcessingException {
Map<String, String> httpHeaders = new HashMap<>();
httpHeaders.put("token", UUID.randomUUID().toString());
String getUrl = "http://localhost:8081/test/api/get?name=jinxudong";
ResponseEntity<String> getResult = getStringResponseEntity(getUrl, "GET", httpHeaders, null);
String body = getResult.getBody();
System.out.println(objectMapper.writeValueAsString(body));
System.out.println("------------------");
String postUrl = "http://localhost:8081/test/api/post";
Map<String, String> jsonObject = new HashMap<>();
jsonObject.put("name", "wangdachui");
jsonObject.put("age", "23");
httpHeaders.put("Content-Type", "application/json");
ResponseEntity<String> postResult = getStringResponseEntity(postUrl, "POST", httpHeaders, objectMapper.writeValueAsString(jsonObject));
System.out.println(">>>>>>>>>>>>>>>>");
System.out.println(objectMapper.writeValueAsString(postResult.getBody()));
String putUrl = "http://localhost:8081/test/api/put";
Map<String, String> jsonObject1 = new HashMap<>();
jsonObject1.put("name", "wangdachui1");
jsonObject1.put("age", "231");
httpHeaders.put("Content-Type", "application/json");
ResponseEntity<String> putResult = getStringResponseEntity(putUrl, "PUT", httpHeaders, "{}");
System.out.println(">>>>>>>>>>>>>>>>PUT");
System.out.println(objectMapper.writeValueAsString(putResult.getBody()));
}