如何使用http://developer.nytimes.com上的Spring Boot获取最新的最新报道
想知道如何使用网址获取最新故事
答案 0 :(得分:0)
为了从Java发出HTTP请求,您应该使用HttpURLConnection
。 NYT的热门新闻api很简单,您应该向以下URL 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();
}