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

标签 java http get

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/

相关文章:

java - pyCharm调试: JRE without jstack?

java - 如何在调用任何 url 时提供 ntlm 身份验证?

java - Java 中的 Boolean.getBoolean() 与 System.getenv()

javascript - 如何在 VueJS 上允许请求 header 字段 access-control-allow-origin

python - 编写一个小而灵活的 HTTP 客户端

java - @PUT Jersey 错误 405 : Method not allowed

java - 如何在其他计算机上运行java可执行文件

get - Twitter API : How to get users ID, 谁最喜欢特定的推文?

java - 返回另一个类的时间

jquery - $(selector).load ('page.html #id' ) 与 $.get 和过滤/查找 #id