我正在尝试使用来自 https://ws-public.interpol.int/notices/v1/red 的 json。邮递员的请求非常有效:
但是当我尝试使用 Spring 的
RestTemplate
时(尝试准确复制请求标头):
final HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CACHE_CONTROL, "no-cache");
headers.set(HttpHeaders.USER_AGENT, "PostmanRuntime/7.42.0");
headers.set(HttpHeaders.HOST, "ws-public.interpol.int");
headers.set(HttpHeaders.ACCEPT, "*/*");
headers.set(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, br");
headers.set(HttpHeaders.CONNECTION, "keep-alive");
final HttpEntity<Void> entity = new HttpEntity<>((Void) null, headers);
final RestTemplate restTemplate = new RestTemplateBuilder()
.interceptors(new HeaderClientHttpRequestInterceptor())
.setConnectTimeout(Duration.ofMillis(5000L))
.setReadTimeout(Duration.ofMillis(5000L))
.build();
final String response = restTemplate
.exchange(URL, HttpMethod.GET, entity, String.class)
.getBody();
我的请求失败并显示 403 Forbidden:
Exception in thread "main" org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: "<HTML><HEAD><LF><TITLE>Access Denied</TITLE><LF></HEAD><BODY><LF><H1>Access Denied</H1><LF> <LF>You don't have permission to access "http://ws-public.interpol.int/" on this server.<P><LF>Reference #18.1cf95568.1730991641.2abc645d<LF><P>https://errors.edgesuite.net/18.1cf95568.1730991641.2abc645d</P><LF></BODY><LF></HTML><LF>"
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:109)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:168)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
at com.company.sample.MySampleApp.main(MySampleApp.java:55)
如何成功模仿Postman的请求?我错过了什么?
试试这个
final RestTemplate restTemplate = new RestTemplateBuilder().setConnectTimeout(
Duration.ofMillis(5000L)).setReadTimeout(Duration.ofMillis(5000L)).build();
final String response = restTemplate.exchange("https://ws-public.interpol.int/notices/v1/red",
HttpMethod.GET, entity, String.class).getBody();