In some cases, I need to disable the long client HTTP polling request. The corresponding part of the HttpUrlConnection that I do on the server is as follows (all the code below is in the Thread run () method):
try {
URL url = new URL(requestURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(60 * 1000);
connection.setRequestMethod("GET");
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
Log.d(TAG, stringBuilder);
} catch (IOException ioe) {
Log.e(TAG, ioe);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
This is how I start first, then (after the second delay) try to cancel the request:
pollThread = new PollThread();
pollThread.start();
Log.d(TAG, "pollThread started");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
pollThread.cancelRequest();
Log.d(TAG, "pollThread presumably cancelled");
}
}, 1000);
And this is what the cancelRequest () method looks like:
public void cancelRequest() {
if (connection != null) {
connection.disconnect();
}
}
So essentially
- I initiate an HttpUrlConnection with a receive request, with 1 minute of waiting to read
- Then after one second I try to cancel the previous request
- The expected result is that the connection should throw an IOException when calling connection.disconnect ()
, (2.2 - 4.0.3), Motorola Atrix (2.3.7) Samsung Note (4.0.1). HTC, 2.2, , , , . HTC Desire HTC Wildfire.
? , 2.2 +?
, -: https://gist.github.com/3306225