[英]How to consume a HTTPS GET service with Spring Boot
我正在嘗試使用Yahoo Weather Service的以下HTTPS端點:
我正在根據API進行一些特殊查詢,以獲取某些參數化位置的當前天氣。
@Service("weatherConditionService")
public class WeatherConditionServiceImpl implements WeatherConditionService {
private static final String URL = "http://query.yahooapis.com/v1/public/yql";
public WeatherCondition getCurrentWeatherConditionsFor(Location location) {
RestTemplate restTemplate = new RestTemplate();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(URL);
stringBuilder.append("?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22");
// TODO: Validate YQL query injection
stringBuilder.append(location.getName());
stringBuilder.append("%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
WeatherQuery weatherQuery = restTemplate.getForObject(stringBuilder.toString(), WeatherQuery.class);
// TODO: Test Json mapping response
Condition condition = weatherQuery.getQuery().getResults().getChannel().getItem().getCondition();
return new WeatherCondition(condition.getDate(), Integer.parseInt(condition.getTemp()), condition.getText());
}
Location是提供屬性“名稱”的類,該屬性是位置的字符串描述,例如“ New York”或“ Manila”。
條件其他類僅映射返回的對象。
執行時,我得到以下HTTP響應:
org.springframework.web.client.HttpClientErrorException: 403 Forbidden
因此,這意味着我無權根據自己的理解訪問資源。
如果我僅將其復制並粘貼到Web瀏覽器中,則該URL會很好用:
我認為映射不是問題,因為我不是“ 400”(錯誤請求)而是“ 403”(禁止訪問)
我使用RestTemplate對象的方式上肯定有一些錯誤。 我正在研究,但找不到答案。
文檔說您需要一個api密鑰。 但是當我這樣打電話時:
fetch('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
.then(resp=> resp.json())
.then((res)=>console.log(res.query.results))
沒有一個就可以正常工作。 也許您因為經常點擊api而被塗黑了。
您的代碼似乎很好。
我終於找到了答案。 最后,它是一個糟糕 的 請求 ,因為我需要以不同的方式傳遞參數(不作為URL的一部分)。
我在這里找到了答案。 這是我特定的Yahoo Weather API調用返回一個String的代碼(我仍然需要做一些工作才能使用映射)。
private static final String URL = "http://query.yahooapis.com/v1/public/yql";
public String callYahooWeatherApi() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(URL)
.queryParam("q", "select wind from weather.forecast where woeid=2460286")
.queryParam("format", "json");
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.GET,
entity,
String.class);
return response.getBody();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.