// 封装 url 并得到返回数据
private ResponseEntity<String> getResponse(String url, Map<String, String> request){
// 它提供了一组方便的方法,可以发送HTTP请求并处理响应
RestTemplate restTemplate = new RestTemplate();
// 创建请求头并设置Content-Type为application/json
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 创建HttpEntity,将请求体和请求头传递给RestTemplate
HttpEntity<Map<String, String>> entity = new HttpEntity<>(request, headers);
// 发送POST请求,并获取返回数据
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
return response;
}
// 将 response 返回解析成 Map
private Map<String, Object> getMap(ResponseEntity<String> response){
// 将response的body字符串解析为一个JsonElement对象
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(response.getBody(), JsonElement.class);
// 使用Gson库将JsonElement对象转换为Map对象
Map<String, Object> resultMap = gson.fromJson(jsonElement, new TypeToken<Map<String, Object>>(){}.getType());
return resultMap;
}
标签:Map,封装,JsonElement,url,ResponseEntity,new,response From: https://www.cnblogs.com/baoguiying/p/17881878.html