【问题标题】:Java reading URL from anapioficeandfire returns 403Java 从 anapioficeandfire 读取 URL 返回 403
【发布时间】:2017-08-21 07:02:27
【问题描述】:

我想用原生 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)

此代码适用于 example.com、google.com 等...

【问题讨论】:

标签: java http url


【解决方案1】:

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

【讨论】:

  • 非常感谢,即使不输入 .openConnection() 到 (HttpURLConnection) 也能正常工作。 URLConnection myUrlConnection = myUrl.openConnection(); myUrlConnection.addRequestProperty("User-Agent", "Mozilla/4.0");
  • 很棒的答案,我知道这与服务器认为我做错了什么有关。我只是不知道要寻找什么。
  • 亚马逊云端需要 httpcon.addRequestProperty("Accept-Encoding", "gzip, deflate, br");
猜你喜欢
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
相关资源
最近更新 更多