使用 RestTemplate
- 将 RestTemplate注入到容器中
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
- 发送get请求
String url = "https://api.example.com/some-endpoint";
String response = restTemplate.getForObject(url, String.class);
return response;
- 发送post请求并设置请求体格式
public String sendHttpPostRequest() {
String url = "https://api.example.com/post-endpoint";
String requestBody = "{\"key\": \"value\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
String response = restTemplate.postForObject(url, requestEntity, String.class);
return response;
}
- 发送文件并添加其他属性
public String sendFileWithProperties() throws IOException {
String url = "https://api.example.com/upload-endpoint";
Path filePath = Paths.get("path/to/your/file.txt");
byte[] fileBytes = Files.readAllBytes(filePath);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new ByteArrayResource(fileBytes) {
@Override
public String getFilename() {
return "file.txt";
}
});
body.add("property1", "value1");
body.add("property2", "value2");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
return responseEntity.getBody();
} else {
return "File upload with properties failed";
}
}