我试图从HttpUrlConnection对象获取响应主体,但当我的服务器没有返回200 OK时就会出现问题。在我的情况下,我得到了302重定向的响应,因此使用getInputStream()
方法不起作用。我尝试使用getErrorStream()
方法,但是由于某些原因,它给我返回了一个空对象。我为什么会得到getErrorStream()
的空对象而不是实际的响应?
public static void main(String[] args) {
String url = "http://www.google.com/";
String proxy = "proxy.myproxy.com";
String port = "8080";
try {
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.connect();
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
InputStream test = connection.getErrorStream();
String result = new BufferedReader(new InputStreamReader(test)).lines().collect(Collectors.joining("\n"));
} catch (Exception e) {
System.out.println(e);
System.out.println("error");
}
}
在我的代码中,我看到的输出是:
Response code:302
Response message:Object Moved
java.lang.NullPointerException
error
具体来说,错误发生在我的尝试语句的最后一行,因为我的
getErrorStream()
返回了一个空对象,因此我得到了一个nullPointerException。有人熟悉这个吗?谢谢。
getInputStream()
应该可以工作吗? - TimerrorStream
是空的HttpURLConnection。 - Piotr S