当输出为空时,BufferedReader卡住

我使用BufferedReader处理网页的输出。当网页的输出为空时(我在网页端使用了Response.Clear),最后一行Log.e("status","finish")无任何作用。 reader.readLine()是否卡在空输出中?如果是,在使用阅读器之前,我应该如何检查响应是否为空?

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); 
connection.setRequestProperty("accept-Charset","utf-8");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + "utf-8");
connection.connect(); // The code works same without this. Do I need this?
try (OutputStream output = connection.getOutputStream()) {
    output.write(query.getBytes("utf-8"));
    Log.e("status","post Done"); // This works
}
InputStream response = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response));

String line="";
while ((line = reader.readLine()) != null) {
    urlData += line;
}
reader.close();

Log.e("status","finish");
inzhatzi 回答:当输出为空时,BufferedReader卡住

是的,它是“被卡住的”,尽管正确的措辞是它是“被阻止的”。它会阻塞直到收到一行文本。当套接字在另一方关闭时,TCP连接将指示终止,并且输入流被关闭。届时,您将检索API指定的null。但是,在这种情况发生之前,高级readLine例程将很乐意等到时间结束或下层生成超时。

因此,如果您不信任服务器连接来返回任何数据,则使用readLine甚至流都不是一个好主意。但是,如果您认为服务器不响应是一个特殊问题,则可以将套接字设置为超时并使用Socket.html#setSoTimeout(int)生成异常。

本文链接:https://www.f2er.com/3129179.html

大家都在问