0
我正在使用Spring Boot開發REST API。我的應用程序依靠第三方REST API來構建結果並將其發送回API的使用者。我無法從REST API應用程序中調用第三方API服務。正如我需要提供API密鑰,我使用的RestTemplate
的exchange(...)
方法如下:使用Spring發送API密鑰@RestTemplate不起作用
@RequestMapping(value="/{userId}",
method = RequestMethod.GET)
public ResponseEntity<String> getUser(@PathVariable String userId,
@RequestHeader String apikey) {
String url = RESTAPIProperties.getUsersUrl() + "https://stackoverflow.com/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的方法和在郵差的apikey
頭提供API密鑰,則請求幾秒後超時。在日誌中,打印了API密鑰和用戶ID,因此我知道restTemplate.exchange(...)
調用第三方服務的內容。但是,如果我直接在Postman中使用相同的API密鑰訪問第三方服務,則會立即收到響應。我錯過了什麼?