由于在工作上遇见了调用接口的需求,在进行代码编写时对于传参有一点小问题,然后对其解决之后,写一篇文章,在以后能够用到。
1.首先
//构建请求头,将token添加到Authorization字段中
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.set("Authorization", token);
headers.setContentType(MediaType.APPLICATION_JSON);
// 构建RestTemplate
RestTemplate restTemplate = new RestTemplate();
//构建请求体
HttpEntity<String> objectHttpEntity = new HttpEntity<>(json,headers);
在构建请求体时需要注意将对象转换成JSON格式,不然在发送请求时会报错。
根据自己传参格式将传参的dto转换为JSON
// 创建一个GsonBuilder对象
GsonBuilder gsonBuilder = new GsonBuilder();
// 自定义日期时间的序列化格式
gsonBuilder.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (localDateTime, type, jsonSerializationContext) ->
jsonSerializationContext.serialize(localDateTime.format(DateTimeFormatter.ISO_DATE_TIME)));
// 将employeeGetByTimeWindowDTO转换成JSON格式
Gson gson = gsonBuilder.create();
String json = gson.toJson(employeeGetByTimeWindowDTO);
发送请求:
ResponseEntity<EmployeeGetByTimeWindowResponse> responseEntity = restTemplate.postForEntity(
requestUrl,
objectHttpEntity,
EmployeeGetByTimeWindowResponse.class
);
这样,一个调用第三方接口的功能就基本实现。希望能够在实现该需求时能够有所帮助!