【发布时间】:2018-02-01 21:19:36
【问题描述】:
每个人。我正在编写一个使用类 HttpURLConnection 连接到服务器的函数。在代码中,我建立了一个连接,依次调用getOutputStream()和getInputStream()方法。然后我断开连接。之后尝试获取getInputStream()方法获取的数据,编译器提示NullPointerException。
代码如下:
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();
}
}
}
调试尝试后,当我将断开连接线移动到 finally 模块的最后一行时,一切都会好起来的。但是我很困惑,当我已经将 'inputstream' 值分配给 'reader' 时会发生这种情况。
非常感谢。
【问题讨论】:
标签: java nullpointerexception connection httpurlconnection inputstreamreader