如何使用http://developer.nytimes.com的弹簧靴获取当前最顶级的故事
想知道如何使用网址来获取当前故事
要从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();
}