我想从 https://anapioficeandfire.com/api/characters/583 获取 Json使用 native Java
代码如下:
import java.net.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws Exception {
URL oracle = new URL("https://anapioficeandfire.com/api/characters/583");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
我得到的是这个错误:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://anapioficeandfire.com/api/characters/583
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at java.net.URL.openStream(URL.java:1045)
at sprint2.fireandice.Main.main(Main.java:17)
此代码适用于 example.com、google.com 等......
最佳答案
问题出在 openStream()
上。服务器拒绝此连接并发送 403 Forbidden。您可以通过设置用户代理来“欺骗”服务器并像普通浏览器一样运行。
public static void main(String[] args) throws Exception{
URL oracle = new URL("https://anapioficeandfire.com/api/characters/583");
HttpURLConnection httpcon = (HttpURLConnection) oracle.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
关于Java 从 anapioficeandfire 读取 URL 返回 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45791071/