RestTemplate是一个用于访问REST服务的Spring框架的模板工具类。它提供了一种方便的方式来与RESTful服务进行通信
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
因为http请求的模板工具类,springboot默认没有自动装配, 直接RestTemplate restTemplate = new RestTemplate();就可以, 不过一般项目中都配置成单例
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
public class MyService {
private final String API_URL = "https://api.example.com/data";
private final RestTemplate restTemplate;
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String fetchData() {
return restTemplate.getForObject(API_URL, String.class);
}
}
public class MyService {
private final String API_URL = "https://api.example.com/data";
private final RestTemplate restTemplate;
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void postData(String data) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(data, headers);
restTemplate.postForObject(API_URL, requestEntity, String.class);
}
}
更复杂场景
public class MyService {
private final String API_URL = "https://api.example.com/data";
private final RestTemplate restTemplate;
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public ResponseEntity<String> fetchDataWithHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer YOUR_ACCESS_TOKEN");
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.GET, entity, String.class);
return response;
}
}
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
int timeout = 5000; // 超时时间,单位为毫秒
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(timeout);
factory.setReadTimeout(timeout);
return factory;
}
}
默认RestTemplate不打印日志,因此我们可以用拦截器实现CustomRequestResponseLoggingInterceptor
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
// 设置ClientHttpRequestFactory为BufferingClientHttpRequestFactory
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
// 创建RestTemplate实例
RestTemplate restTemplate = new RestTemplate(factory);
// 添加自定义的ClientHttpRequestInterceptor用于记录请求和响应日志
restTemplate.setInterceptors(Collections.singletonList(new CustomRequestResponseLoggingInterceptor()));
return restTemplate;
}
private static class CustomRequestResponseLoggingInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
// 打印请求日志
System.out.println("Request: " + request.getMethod() + " " + request.getURI());
// 打印请求头
System.out.println("Request Headers: " + request.getHeaders());
// 打印请求body(如果有的话)
if (body.length > 0) {
System.out.println("Request Body: " + new String(body, Charset.defaultCharset()));
}
// 执行请求
ClientHttpResponse response = execution.execute(request, body);
// 打印响应日志
System.out.println("Response Status Code: " + response.getStatusCode());
// 打印响应body(如果有的话)
String responseBody = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
if (!responseBody.isEmpty()) {
System.out.println("Response Body: " + responseBody);
}
return response;
}
}
}
public class FileService {
private final RestTemplate restTemplate;
public FileService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void uploadFile(String apiUrl, File file) {
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
restTemplate.exchange(apiUrl, HttpMethod.POST, new RequestCallback() {
@Override
public void doWithRequest(org.springframework.http.client.ClientHttpRequest request) {
request.getHeaders().addAll(headers);
}
}, new ResponseExtractor<ResponseEntity<String>>() {
@Override
public ResponseEntity<String> extractData(org.springframework.http.client.ClientHttpResponse response) {
// Handle response if needed
return null;
}
}, body);
}
}
public class FileService {
private final RestTemplate restTemplate;
public FileService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void downloadFile(String apiUrl, String savePath) throws IOException {
ResponseEntity<Resource> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.GET, new RequestCallback() {
@Override
public void doWithRequest(org.springframework.http.client.ClientHttpRequest request) {
// Set headers if needed
}
}, Resource.class);
Resource resource = responseEntity.getBody();
if (resource != null) {
Path filePath = Path.of(savePath);
Path parentDir = filePath.getParent();
// 创建父目录
if (parentDir != null && !Files.exists(parentDir)) {
Files.createDirectories(parentDir);
}
// 保存文件
Files.copy(resource.getInputStream(), filePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
}
}