当我使用函数查询 InputStream 然后 return 它时,它自动关闭
When I use a function to query an InputStream and then return it, it automatically closed
public InputStream executeQuery(String query) throws IOException {
if(!networkTest()){
return null;
}
HttpURLConnection httpURLConnection = null;
URL url = new URL(query);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
return in;
}
代码return 一个关闭的输入流,但是在这个函数内部,输入流没有关闭。为什么?
您应该在断开连接之前从输入流中读取数据,因为它会关闭关联的流。
您可以使用此代码在关闭连接之前读取响应。
public String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
public InputStream executeQuery(String query) throws IOException {
if(!networkTest()){
return null;
}
HttpURLConnection httpURLConnection = null;
URL url = new URL(query);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
return in;
}
代码return 一个关闭的输入流,但是在这个函数内部,输入流没有关闭。为什么?
您应该在断开连接之前从输入流中读取数据,因为它会关闭关联的流。
您可以使用此代码在关闭连接之前读取响应。
public String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}