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;
}
代码返回一个关闭的输入流但在此函数内部时,输入流未关闭。为什么呢?
答案 0 :(得分:0)
在断开连接之前,您应该从输入流中读取数据,因为它会关闭相关的流。
您可以在关闭连接之前使用此代码读取响应。
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();
}