[BufferedReader在输出为空时被卡住

问题描述 投票:0回答:1

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

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");
android bufferedreader urlconnection
1个回答
1
投票

是的,它被“卡住”,尽管正确的措词是“被阻止”。它会阻塞直到收到一行文本。当套接字在另一方关闭时,TCP连接将指示终止,并且输入流被关闭。此时,您将检索API指定的null。但是,在此之前,高层readLine例程将愉快地等待,直到时间结束,或者直到下一层生成超时为止。

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

© www.soinside.com 2019 - 2024. All rights reserved.