尝试获取InputStream时获取错误502/504

时间:2013-12-16 08:25:26

标签: 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()

有什么想法吗?

我们将不胜感激。 提前致谢

1 个答案:

答案 0 :(得分:1)

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要容易得多。