如何使用http://developer.nytimes.com上的spring boot获取当前最顶级的故事

问题描述 投票:0回答:1

如何使用http://developer.nytimes.com的弹簧靴获取当前最顶级的故事

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

spring spring-boot
1个回答
0
投票

要从Java发出HTTP请求,您应该使用HttpURLConnection。顶级故事的NYT api非常简单,您应该向以下网址GET发送String url = https://api.nytimes.com/svc/topstories/v2/home.json?api-key=" + apiKey请求,其中必须从NYT请求apiKey。

以下方法执行请求并将响应作为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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.