如果我有一个java.net.HttpURLConnection
在工作线程中接收数据(或即将接收数据),可以安全地呼叫disconnect()
在另一个线程的连接生命周期的任何时刻停止它?可以从另一个线程安全地调用disconnect()来取消正在进行的HttpURLConnection?
我想知道这个,因为我找不到一个明确记录的方式来中止正在进行的HTTP连接。通过调用Thread.interrupt()
中断工作线程将不起作用,因为从HttpURLConnection
获得的InputStream
不可中断。
我做了一些实验是这样的:
// MyRequest.run() gets an HttpURLConnection by calling someUrl.openConnection()
MyRequest request = new MyRequest(someUrl);
FutureTask<SomeResult> task = new FutureTask<SomeResult>(request);
someExecutor.execute(task);
// The connection opens, data comes in, ...
// Get the HttpURLConnection from the request, call disconnect()
// Should be part of the cancel() of a FutureTask subclass
request.getConnection().disconnect();
看来工作,并且两个连接,它创建的Socket对象将通过GC最终被清理。不过,我想知道这是否是正确的做法?从另一个线程调用disconnect()
会有什么问题吗?
要解决此限制,请在[Future]中包含使用'HttpURLConnection'的代码,如[此处](http://stackoverflow.com/a/26489077/145173)所述。 –