它可以停止正在连接到URL以httpConnection

它可以停止正在连接到URL以httpConnection

本文介绍了它可以停止正在连接到URL以httpConnection.connect()线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到一个URL来获取一些数据的线程。

i have a thread that is connecting to a url to obtaining some data.

有时方法 httpConnection.connect(); 抽放太蒙克时间得到响应,而我想这个连接线程加载对话框限制在5 SEG。

Sometimes the method httpConnection.connect(); taked too munch time to get the response, and i want to limit the loading dialog of this connection thread to 5 seg.

我trye​​d将超时到code,,但它不能正常工作

I tryed adding timeouts into the code, but it doesn't work!!

URL formattedUrl = new URL(url);
            URLConnection connection = formattedUrl.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.setRequestMethod("GET");
            httpConnection.setConnectTimeout(5000);
            httpConnection.setReadTimeout(5000);
            httpConnection.connect();

所以,我必须在5000秒已通过或当使用具有pressed手机上的返回键停止连接方法和线程。

So, i must stop the connect method and the thread when 5000 seconds have passed or when the used has pressed the back key on the phone.

如何才能实现这一目标?我无法找到一个URL连接线程做这项工作在android系统的信息。

How can this be achieved? i can't find info about doing this work in android with a url connection thread.

感谢

推荐答案

布伦特·沃登的答案是正确的轨道上。但存在与他的溶液的问题。如果任务超时踢,调用线程的Future.get 将如预期得到一个异常。但是,这是执行 Runnable.run()方法的工作线程的可能的还是被卡住等待连接或阅读来完成。

Brent Worden's answer is on the right track. But there is a problem with his solution. If the task timeout kicks in, the thread that called future.get will get an exception as expected. However, the worker thread that was executing the Runnable.run() method may still be stuck waiting for the connect or read to complete.

求解这是困难的。据我所知,到unjam这是一个套接字上等待的线程连接或套接字流读或写的唯一可靠方法是调用的close()插座对象。并使用这种方法(在这里)的问题是,标准的 HttpURLConnection类对象不公开的插座对象。

Solving this is difficult. As far as I'm aware, the only reliable way to unjam a thread that is waiting on a socket connect or socket stream read or write is to call close() on the Socket object. And the problem with using that approach (here) is that the standard HttpUrlConnection object doesn't expose the Socket object.

我的建议是使用的Apache HTTP客户端库。这个问题说明了,如果你使用的HttpClient如何中止请求:

My recommendation would be to use the Apache Http client libraries. This question explains how to abort a request if you use HttpClient: Cancel an HttpClient request

这篇关于它可以停止正在连接到URL以httpConnection.connect()线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:31