2017-11-02 2 views
0

내가 야후 날씨 서비스에서 다음 HTTPS 끝점을 소비하는 것을 시도하고있다 :봄 부트와 HTTPS GET 서비스를 사용하는 방법

Yahoo Weather Service API

내가 전류를 얻을 수있는 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()); 
    } 

위치는 "뉴욕"또는 "마닐라"와 같은 위치의 캐릭터의 설명이다 속성 "이름"을 제공하는 클래스입니다.

조건 다른 클래스는 반환 객체를 매핑합니다.

org.springframework.web.client.HttpClientErrorException: 403 Forbidden 

그래서 이것이 내가 내가 이해에서 리소스에 액세스 할 수있는 권한이 없습니다하고 의미 실행할 때

나는 다음과 같은 HTTP 응답을 얻을. 난 그냥 &를 복사 할 경우

URL은 웹 브라우저에 붙여 넣으 좋은 작품 : 나는 매핑 내가지고 있지 않다 때문에 문제 "400"(잘못된 요청)이 아니라고 생각

Yahoo Weather Query

하지만, "403"(금지됨)

RestTemplate 개체를 사용하는 방법에 오류가 있어야합니다. 조사 중이지만 답변을 찾을 수 없습니다.

답변

0

마침내 대답을 찾았습니다. 마지막으로 WAS a 잘못된 요청 (URL의 일부가 아닌) 매개 변수를 다르게 전달해야했기 때문입니다.

대답은 here입니다. 여기 야후 날씨 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(); 

    } 
1

문서에는 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)) 

https://repl.it/NeoM

합니다. 어쩌면 당신은 API를 너무 자주 치는 것에 대해 흑인 주의자 였을 것입니다.

코드가 정상적으로 보입니다.

+0

감사합니다. 나는 자바 스크립트를 사용하거나 웹 브라우저에 직접 충돌 할 수있다. Java 예제가 없으므로 API 키가 필요 없다고 생각했습니다. 그럴 수 있습니다. Java에서이를 수행하는 방법을 확인해야합니다. – sebadagostino

관련 문제