开发过程用用到处理restTemplate
@Component
public class UriRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
// 获取原始请求的URI
URI originalUri = request.getURI();
// 修改或替换URL
String url = originalUri.toString();
int start = url.indexOf("gateway")-1;
int end = url.indexOf("/bim-base");
// 确保start和end位置有效
String modifiedUrl;
if (start != -1 && end != -1) {
String replaceStr = url.substring(start, end);
modifiedUrl = StringUtils.replace(originalUri.toString(), replaceStr, "");
assert modifiedUrl != null;
URI newUri = URI.create(modifiedUrl);
// 创建一个新地请求对象,并设置新的URI
HttpRequest modifiedRequest = new HttpComponentsClientHttpRequestFactory().createRequest(newUri, Objects.requireNonNull(request.getMethod()));
// 将原请求的所有头信息复制到新请求中
HttpHeaders headers = modifiedRequest.getHeaders();
for (String headerName : request.getHeaders().keySet()) {
headers.add(headerName, request.getHeaders().getFirst(headerName));
}
// 使用新的请求执行HTTP操作
return execution.execute(modifiedRequest, body);
}else {
// 可以抛出异常或者返回一个错误的HttpResponse
throw new IllegalArgumentException("UriRequestInterceptor-修改替换URL异常!");
}
}
然后配置类restTempalte添加拦截器
RestTemplate build = new RestTemplateBuilder(restTemplateCustomizer).build();
// 添加拦截器 针对RestTemplate请求进行拦截
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new UriRequestInterceptor());
build.setInterceptors(interceptors);