IOException:流被关闭,NullPointerException与HttpURLConnection断开连接
问题描述:
everyone。我正在编写一个使用Class HttpURLConnection连接到服务器的函数。在代码中,我建立了一个连接,按顺序调用getOutputStream()和getInputStream()方法。然后我断开连接。在此之后,我尝试获取通过getInputStream()方法获得的数据,但编译器会提醒NullPointerException。IOException:流被关闭,NullPointerException与HttpURLConnection断开连接
代码如下:
DataOutputStream out = null;
InputStreamReader inStrReader = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL postUrl = new URL(null, url, new sun.net.www.protocol.https.Handler());
connection = (HttpURLConnection) postUrl.openConnection();
...//some setting methods
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(JSONObject.toJSONString(param));
out.flush();
out.close();
inStrReader = new InputStreamReader(connection.getInputStream(), "utf-8");
reader = new BufferedReader(inStrReader);
connection.disconnect(); //<--HERE, release the connection
StringBuilder stringBuilder = new StringBuilder();
for (String line = reader.readLine(); line != null; line = reader.readLine()) { //<--null pointer
stringBuilder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inStrReader != null) {
try {
inStrReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
调试尝试后,当我移动断开线终于模块中的最后一行,一切都会好的。但是我很困惑,这发生在我已经将“输入流”的价值转嫁给“读者”时。
非常感谢。
答
指定不等于读数,reader.readLine()
开始从连接读取。
InputStreamReader使用连接读取的字节,断开之前,使用连接
InputStreamReader是字节流通向字符 流的桥梁读取的字节中:它读取字节,并...
答
你正在做的所有事情都是错误的。这没有意义。
您正在断开连接,然后希望能够从连接中读取数据。这里总是废话。通常情况下,您不应该断开连接,因为您会干扰HTTP连接池。只要删除它,或者,如果您必须拥有它,请在完成所有关闭之后再进行操作。
您正在以错误的顺序关闭,但您根本不需要关闭
inStrReader
。关闭BufferedReader
即可。请删除inStrReader.close()
的所有代码。您正在关闭
out
两次。不要这样做。connect()
含蓄地发生。你不需要自己调用它。new URL(url)
就足够了。你有没有需要提供HTTPSHandler
距今约2003年
断开之前,我已经得到了InputStream对象为变量“读者”。但是,当我调试时,reader.readLine()方法获得nullpointexception。 – phinux
但你没有看过任何东西,为了读取连接应该打开,因为你正在阅读使用它 – user7294900