2017-09-01 39 views
0

我正在学习Java和SpringBoot。试图制作一个网络应用程序来检查天气。我正在使用来自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使用弹簧启动(它会在语言环境中输入窗体上工作)。

回答

0

Spring documentation "Consuming a RESTful Web Service"

本指南将引导您完成创建消耗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会自动从API转换成JSON Java对象。