gpt4 book ai didi

Java 从 anapioficeandfire 读取 URL 返回 403

转载 作者:可可西里 更新时间:2023-11-01 16:59:55 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com