配置
/**
* @Author: gaoxinyu
* @Date: 2025/6/8 9:59
* @Version: 1.0
**/
@Configuration
public class RestConfig {
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000); // 连接超时15秒
factory.setReadTimeout(5000); // 读取超时5秒
return factory;
}
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
MyInterceptor myInterceptor = new MyInterceptor();
List<ClientHttpRequestInterceptor> interceptorList = List.of(myInterceptor);
restTemplate.setInterceptors(interceptorList);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
return restTemplate;
}
}
@Slf4j
class MyInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
log.info("请求 URL: {}", request.getURI());
log.info("请求方法: {}", request.getMethod());
log.info("请求体内容: {}", new String(body, StandardCharsets.UTF_8));
// 给请求添加鉴权Header
request.getHeaders().add("Authorization", "sanjin521");
// 发送请求
ClientHttpResponse response = execution.execute(request, body);
log.info("响应状态码: {}", response.getStatusCode());
// 注意:如果需要读取响应体,代码要额外处理响应流
return response;
}
}
@Slf4j
class MyResponseErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
// 判断响应是否错误
return response.getStatusCode() != HttpStatus.OK;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
log.error("响应错误,状态码: {}, 响应体: {}", response.getStatusCode(), StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
// 统一处理错误,比如解析错误体,抛出自定义异常
// throw new GlobalException("xxx");
// 你可以根据状态码和响应体,抛出不同异常
}
}
简单的api使用
@Data
class GoStopRequest {
private Long trainId;
}
@Autowired
private RestTemplate restTemplate;
@GetMapping("/go")
public void test() {
// 无参数
String url1 = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/ping").toUriString();
ResponseEntity<String> res1 = restTemplate.getForEntity(url1, String.class);
// ?传参 http://localhost:8080/getProcess?tarinId=6
String url2 = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getProcess").queryParam("trainId", 6).toUriString();
ResponseEntity<JSONObject> res2 = restTemplate.getForEntity(url2, JSONObject.class);
// 路径传参
String url3 = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/process/{trainId}/detail/{detailId}").buildAndExpand(6, 10).toUriString();
ResponseEntity<JSONObject> res3 = restTemplate.getForEntity(url3, JSONObject.class);
// post请求体传参, get没有请求体
String url4 = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/stop").toUriString();
GoStopRequest params1 = new GoStopRequest();
params1.setTrainId(6L);
ResponseEntity<JSONObject> res4 = restTemplate.postForEntity(url4, params1, JSONObject.class);
System.out.println(res4.getStatusCode());
System.out.println(res4.getBody());
System.out.println(res4.getHeaders());
// 使用exchange为请求添加header
String url5 = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/add").toUriString();
JSONObject params2 = new JSONObject();
params2.put("trainId", 6);
RequestEntity<JSONObject> entity = RequestEntity.post(URI.create(url5))
.accept(MediaType.ALL)
.contentType(MediaType.ALL)
.header("token", "123456")
.body(params2);
ResponseEntity<JSONObject> exchange = restTemplate.exchange(entity, JSONObject.class);
}