【问题标题】:Beginner - Springboot weather program初学者——Springboot天气程序
【发布时间】:2018-02-10 16:33:42
【问题描述】:

我正在学习 Java 和 SpringBoot。试图制作一个网络应用程序来检查天气。我正在使用来自https://openweathermap.org/api 的 API。

我不知道如何从 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 boot(它可以在区域设置输入的表单上工作)。

【问题讨论】:

    标签: java json spring-boot weather-api


    【解决方案1】:

    来自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 会自动将 JSON 从 API 转换为 Java 对象。

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多