android– 如何断开HTC(Froyo及以下)手机上的HttpUrlConnection?

android– 如何断开HTC(Froyo及以下)手机上的HttpUrlConnection?,第1张

概述在某些情况下,我需要从客户端断开长轮询http请求.我对服务器的HttpUrlConnection的相关部分如下(以下所有代码都在Thread的run()方法中):try { URL url = new URL(requestURL); connection = (HttpURLConnection) url.openConnection(

在某些情况下,我需要从客户端断开长轮询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();        }    }}

这是我第一次启动,然后(在第二次延迟后)尝试取消请求:

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);

这就是cancelRequest()方法的样子:

public voID cancelRequest() {    if (connection != null) {        connection.disconnect();    }}

基本上,

>我使用get请求启动httpUrlConnection,读取超时为1分钟
>然后一秒钟后,我尝试取消之前的请求
>预期的结果是,当我调用connection.disconnect()时,连接应抛出IOException

这正是各种仿真器(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中修复:

Issue 11705: impossible to close HTTP connection using HttpURLConnection

如何在运行2.2的所有设备上安全取消此类请求?

该链接中项目成员的评论:

The best approximation of this that will work in current releases is to set read and connect timeouts on the http connection.

希望有所帮助. 总结

以上是内存溢出为你收集整理的android – 如何断开HTC(Froyo及以下)手机上的HttpUrlConnection?全部内容,希望文章能够帮你解决android – 如何断开HTC(Froyo及以下)手机上的HttpUrlConnection?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1140052.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存