And*_*ázi 5 android httpurlconnection disconnect android-2.2-froyo
在某些情况下,我需要从客户端断开长轮询http请求.我对服务器的HttpUrlConnection的相关部分如下(以下所有代码都在Thread的run()方法中):
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");
// read the output from the server
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我第一次启动,然后(在第二次延迟后)尝试取消请求:
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);
Run Code Online (Sandbox Code Playgroud)
这就是cancelRequest()方法的样子:
public void cancelRequest() {
if (connection != null) {
connection.disconnect();
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,
这正是各种仿真器(2.2 - 4.0.3),摩托罗拉Atrix(2.3.7)和三星Note(4.0.1)上发生的情况.但是在一些运行2.2的HTC设备上,尽管我明确终止了连接,但请求仍将保持活动并且它将收到响应.我用HTC Desire和HTC Wildfire验证了这一点.
这里发生了什么?如何在所有运行2.2+的设备上安全取消此类请求?
为方便起见,如果您想自己试驾,可以在这里找到整个代码:https://gist.github.com/3306225
这是早期 android 版本(Froyo 2.2)中的一个已知错误,在某种程度上,套接字无法由其他线程异步关闭,并且已在 Gingerbread 2.3 中修复:
问题 11705:无法使用 HttpURLConnection 关闭 HTTP 连接
该链接中项目成员的评论:
在当前版本中,对此的最佳近似是在 HTTP 连接上设置读取和连接超时。
希望有帮助。
归档时间: |
|
查看次数: |
2133 次 |
最近记录: |