有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

http Java从anapioficeandfire读取URL返回403

我想用本机Java从https://anapioficeandfire.com/api/characters/583获取Json

以下是代码:

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)

此代码与示例一起使用。com,谷歌。com等等


共 (1) 个答案

  1. # 1 楼答案

    问题在于openStream()。服务器拒绝此连接并发送403禁止。你可以通过设置一个用户代理来“愚弄”服务器,像普通的浏览器一样

    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();
    }