2017-09-01 21 views
0

私はJavaとSpringBootを学んでいます。天気をチェックするためのWebアプリケーションを作成しようとしています。私はhttps://openweathermap.org/apiからAPIを使用しています。初心者 - Springbootの天気プログラム

API(JSON)からデータを取得する方法がわかりません。誰かが私に何か教えてもらえますか?

public String connectAndResponse(String url) throws IOException { 

    StringBuilder stringBuilder = new StringBuilder(); 
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(
      connection.getResponseCode()==200 ? connection.getInputStream() : connection.getErrorStream() 
    )); 

    String line = ""; 
    while((line = reader.readLine()) !=null){ 
     stringBuilder.append(line); 
    } 
    return stringBuilder.toString(); 
} 

私はすでに文字列でJSONを処理してきたが、私は(それは、ロケールが入力され、フォーム上で動作します)春のブートを使用するようにJSONを使用する方法がわかりません。 Spring documentation "Consuming a RESTful Web Service"から

答えて

0

このガイドでは、RESTfulなWebサービスを消費アプリケーション を作成するプロセスを説明します。

まず、モデルを定義する必要があります。この場合、それはQuoteValueです。

次に、APIを呼び出すことができます。ここで

は例です:

public class Application { 

    private static final Logger log = LoggerFactory.getLogger(Application.class); 

    public static void main(String args[]) { 
     RestTemplate restTemplate = new RestTemplate(); 
     Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); 
     log.info(quote.toString()); 
    } 

} 

RestTemplateは自動的にJavaオブジェクトにAPIからJSONを変換します。