我正在使用Spring Boot开发REST API。我的应用程序依赖于第三方REST API来构建结果,并将其发送回API的使用者。我在从REST API应用程序调用第三方API服务时遇到问题。因为我需要提供一个API key,所以我使用RestTemplate
的exchange(...)
方法,如下所示:
@RequestMapping(value="/{userId}",
method = RequestMethod.GET)
public ResponseEntity<String> getUser(@PathVariable String userId,
@RequestHeader String apikey) {
String url = RESTAPIProperties.getUsersUrl() + "/users/{userId}";
// Set headers for the request
Map<String,Object> headersMap = Collections.unmodifiableMap(
Stream.of(
new SimpleEntry<>("apikey", apikey),
new SimpleEntry<>("Accept", "application/json")
)
.collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
HttpEntity<?> httpEntity = buildHttpEntity(headersMap);
log.info("API Key: {}, Call sign: {}", apikey, userId);
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, userId);
}
// Returns HttpEntity object with the specified headers set
private HttpEntity<String> buildHttpEntity(Map<String,Object> headerParams) {
HttpHeaders headers = new HttpHeaders();
headerParams.forEach((k,v)->headers.set(k, v.toString()));
return new HttpEntity<String>(headers);
}
当我使用GET调用API方法并在Postman的apikey
头中提供API key时,请求在几秒钟后超时。在日志中,打印了API键和用户ID,因此我知道对第三方服务的restTemplate.exchange(...)
调用有问题。但是,如果我在Postman中使用相同的API密钥直接访问第三方服务,则会立即收到响应。我遗漏了什么?
发布于 2016-11-19 02:41:03
事实证明这不是一个问题;这是一个缺失的代理服务器设置。一旦我弄清楚了这一点,我将以下代码添加到Catalina脚本中,一切都运行得很好。
JAVA_OPTS="-Dhttps.proxySet=true \
-Dhttps.proxyHost=proxy.company.com \
-Dhttps.proxyPort=2345 $JAVA_OPTS"
https://stackoverflow.com/questions/40667533
复制相似问题