I used BufferedReader to proccess the output of a webpage. When the output of webpage is empty (I used Response.Clear
in web side), the last line Log.e("status","finish")
does nothing. Is reader.readLine()
being stucked in empty output? If yes, how should I check if response is empty before using a reader?
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");
Yes, it is "stucked", although the correct wording is that it is "blocked". It blocks until it receives a line of text. When the socket is closed at the other party, the TCP connection will indicate termination and the input stream gets closed. At that point you would retrieve null
as specified by the API. However, before that happens the high level readLine
routine will happily wait until the end of time, or until a time-out is generated by a lower layer.
As such, it might not be a good idea to use readLine
or even stream if you don't trust your server connection to return any data. You can however set the socket to time-out and generate an exception instead using Socket.html#setSoTimeout(int)
- if you think that the server not responding is an exceptional problem.