首页 > 解决方案 > 如何使用来自 http://developer.nytimes.com 的 Spring Boot 获取当前最热门的故事

问题描述

如何使用来自http://developer.nytimes.com的 Spring Boot 获取当前最热门的故事

想知道如何使用 url 来获取当前故事

标签: springspring-boot

解决方案


为了从 Java 发出 HTTP 请求,您应该使用HttpURLConnection. NYT 头条新闻的 api 非常简单,您应该向GET以下 URL 发送请求String url = https://api.nytimes.com/svc/topstories/v2/home.json?api-key=" + apiKey,其中 apiKey 必须从 NYT 请求。

以下方法执行请求并将响应返回为String

public String getTopStories(String apiKey) throws Exception {
        URL url = new URL("https://api.nytimes.com/svc/topstories/v2/home.json?api-key=" + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int statusCode = connection.getResponseCode();
        if (statusCode != HttpStatus.OK.value()) {
            throw new Exception("NYT responded with:" + statusCode);
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line+"\n");
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }

推荐阅读