gpt4 book ai didi

java - 尝试获取 InputStream 时出现错误 502/504

转载 作者:行者123 更新时间:2023-12-01 13:42:28 25 4
gpt4 key购买 nike

URL queryUrl = new URL(url);
InputStream inputStream = null;
HttpsURLConnection connection = (HttpsURLConnection) queryUrl.openConnection();
connection.setRequestProperty("User-Agent", "My Client");
connection.setRequestMethod("GET");
connection.setDoInput(true);
inputStream = connection.getInputStream();

嗨,我正在使用上面的代码来执行 HttpGet 查询。我在几次尝试中遇到一次异常,服务器返回错误代码 502 或 504(两种情况都会发生)。异常在行中抛出:

inputStream = connection.getInputStream()

有什么想法吗?

您的帮助将不胜感激。提前致谢

最佳答案

5xx 中的错误代码表示服务器或代理存在一些问题。 RFC 声明

Response status codes beginning with the digit "5" indicate cases in which the server is 
aware that it has erred or is incapable of performing the request. Except when responding
to a HEAD request, the server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent condition. User agents SHOULD
display any included entity to the user. These response codes are applicable to any request method.

请通过读取url连接的错误流来检查实际错误是什么,如下所示:如果 HTTP 响应代码是 4nn(客户端错误)或 5nn(服务器错误),那么您可能需要读取 HttpURLConnection#getErrorStream() 以查看服务器是否发送了任何有用的错误信息。

InputStream error = ((HttpURLConnection) connection).getErrorStream();   

此外,我认为要处理 http 请求,您可以使用 Apache HttpClient,而不是直接使用 HttpUrlConnection。使用 HttpClient 更容易。

关于java - 尝试获取 InputStream 时出现错误 502/504,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20606305/

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