我正试着阅读来自
https://mtgjson.com/api/v5/AllPrintings.json
。我已尝试使用此代码:
url = new URL("https://mtgjson.com/api/v5/AllPrintings.json");
conn = (HttpsURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // error here
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
System.out.println(content);
我一直使用BufferedReader(conn.getInputStream())获取IOException。url中的文本不包含换行符。如何读取这些数据?
编辑
我使用的是Java 1.8和Apache NetBeans 16。我坚持使用1.8,所以我也可以使用Eclipse Neon3。
错误
java.io.IOException: Server returned HTTP response code: 403 for URL: https://mtgjson.com/api/v5/AllPrintings.json
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at tests.MtgJson.main(MtgJson.java:44)
我也一直在尝试使用curl的ProcessBuilder,它给出了更好的结果,但大约一分钟后curl就停止了。如果我终止了Netbeans内部的程序,但并不总是完成文件内容的创建,那么Curl就会继续。我不应该为了curl的继续而停止我的程序。我是不是缺少什么东西让curl去上班?
String command = "curl --keepalive-time 5 https://mtgjson.com/api/v5/AllPrintings.json";
ProcessBuilder pb = new ProcessBuilder(command.split(" "));
pb.redirectOutput(new File("AllPrintings.json"));
Process process = pb.start();
// use while() or process.waitfor();
while(process.isAlive())
Thread.sleep(1000);
process.destroy();
答案(因为我不能发布):
String command = "curl https://mtgjson.com/api/v5/AllPrintings.json";
ProcessBuilder pb = new ProcessBuilder(command.split(" "));
pb.inheritIO(); // keep the program from hanging
pb.redirectOutput(new File("AllPrintings.json"));
Process process = pb.start();
process.waitFor(); // waiting for the process to terminate.
完整的文件在不挂起的情况下创建,然后程序将关闭。Curl将信息输出到控制台,并且必须被消耗
(found here)
.