用RestTemplate模仿Postman的请求失败

问题描述 投票:0回答:1

我正在尝试使用来自 https://ws-public.interpol.int/notices/v1/red 的 json。邮递员的请求非常有效:

Postman request

但是当我尝试使用 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&#58;&#47;&#47;ws&#45;public&#46;interpol&#46;int&#47;" on this server.<P><LF>Reference&#32;&#35;18&#46;1cf95568&#46;1730991641&#46;2abc645d<LF><P>https&#58;&#47;&#47;errors&#46;edgesuite&#46;net&#47;18&#46;1cf95568&#46;1730991641&#46;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的请求?我错过了什么?

java spring resttemplate
1个回答
0
投票

试试这个

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();
© www.soinside.com 2019 - 2024. All rights reserved.