从我自己的 API 获取 JSON 后,我想将 JSON 转换为 CSV API。JSON to CSV API 需要在 POST 请求中传递电子邮件和 JSON。现在我可以在本地存储 JSON,但是,如何在请求中同时传递电子邮件和 JSON,以及如何处理响应中的 CSV?
控制器
@PostMapping("/generateExcel")
public String getEmployeeCsv(@RequestBody String email) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String json = restTemplate.exchange("http://localhost:8080/SwaggerTest/employees", HttpMethod.GET, entity, String.class).getBody();
entity = new HttpEntity<String>(json, email, headers);
return restTemplate.exchange("https://json-csv.com/api/getcsv", HttpMethod.POST, entity, String.class).getBody();
}
更新:
我按照@Adrien 的建议创建了一个EmployeeCsvParams
包含电子邮件和 json 字符串字段的类,但我仍然需要处理响应中的 CSV。
@PostMapping("/generateExcel")
public String getEmployeeCsv(@RequestBody String email) {
HttpHeaders headers = new HttpHeaders();
EmployeeCsvParams params = new EmployeeCsvParams();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String json = restTemplate.exchange("http://localhost:8080/SwaggerTest/employees", HttpMethod.GET, entity, String.class).getBody();
params.setEmail(email);
params.setJson(json);
HttpEntity<EmployeeCsvParams> entity2 = new HttpEntity<EmployeeCsvParams>(params, headers);
return restTemplate.exchange("https://json-csv.com/api/getcsv", HttpMethod.POST, entity2, String.class).getBody();
}