Java 从 anapioficeandfire 读取 URL 返回 403

标签 java http url

我想从 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/

相关文章:

java - 可以按值的顺序迭代的映射

链表中的Java算法

HTTP 范围 header

java - 文本未保存到字符串变量

php - 使用 PHP 从 URL 中获取 "property og"元标记

java - keyPressed 监听器产生奇怪的行为

angularjs - 使用 angular 的 $http.put 发送数据错误

javascript - Angular JSON post 只发送 json 数组的一项

c# - 如何验证 URL 位置是否存在?

java - 嵌套 for 循环错误,使用 !null 检查不存在的元素