来自anapioficeandfire的Java读取URL返回403

时间:2017-08-21 07:02:28

标签: java http url

我希望Json从https://anapioficeandfire.com/api/characters/583获得本地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等...

1 个答案:

答案 0 :(得分:2)

问题在于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();
}