问题描述
我使用的是广场的改造客户端,使从Android应用程序短暂的JSON请求。有没有办法取消的请求?如果是这样,怎么样?
I'm using Square's Retrofit Client to make short-lived json requests from an Android App. Is there a way to cancel a request? If so, how?
推荐答案
有关取消异步的改造要求,您可以通过关闭 ExectorService 执行异步请求
For canceling async Retrofit request, you can achieve it by shutting down the ExectorService that performs the async request
例如我有这个code建 RestAdapter
:
For example I had this code to build the RestAdapter
:
Builder restAdapter = new RestAdapter.Builder();
restAdapter.setEndpoint(BASE_URL);
restAdapter.setClient(okClient);
restAdapter.setErrorHandler(mErrorHandler);
mExecutorService = Executors.newCachedThreadPool();
restAdapter.setExecutors(mExecutor, new MainThreadExecutor());
restAdapter.setConverter(new GsonConverter(gb.create()));
和有这种方法,有力地放弃请求:
and had this method for forcefully abandoning the requests:
public void stopAll(){
List<Runnable> pendingAndOngoing = mExecutorService.shutdownNow();
// probably await for termination.
}
另外,你可以做一个使用 ExecutorCompletionService
的,要么调查(超时,TimeUnit.MILISECONDS)
或取()
所有正在进行的任务。这将prevent线程池没有被关闭,因为这将与执行shutdownNow()
,所以你可以重用你的的ExecutorService $做C $ C>
Alternatively you could make a use of ExecutorCompletionService
and either poll(timeout, TimeUnit.MILISECONDS)
or take()
all ongoing tasks. This will prevent thread pool not being shut down, as it would do with shutdownNow()
and so you could reuse your ExecutorService
希望这将是对别人的帮助。
Hope it would be of help for someone.
修改:作为OkHttp 2 RC1 的changelog 执行。取消(对象标签)
是可能的。我们应该期待在即将到来的改造同样的功能:
Edit: As of OkHttp 2 RC1 changelog performing a .cancel(Object tag)
is possible. We should expect the same feature in upcoming Retrofit:
您可以使用实际要求
对象,将其取消
You can use actual Request
object to cancel it
okClient.cancel(要求);
如果您所提供的标签 Request.Builder
你必须使用
or if you have supplied tag to Request.Builder
you have to use
okClient.cancel(request.tag());
所有正在进行的,执行或挂起请求在调度排队
, okClient.getDispatcher()
。你可以调用这个对象的取消方法了。取消法将通知okhttp 引擎
杀连接到主机上,如果已经建立。
All ongoing, executed or pending requests are queued inside Dispatcher
, okClient.getDispatcher()
. You can call cancel method on this object too. Cancel method will notify okhttp Engine
to kill the connection to the host, if already established.
编辑2 :改造2已经全面功能的取消请求。
Edit 2: Retrofit 2 has fully featured canceling requests.
这篇关于利用广场的改造客户,是否有可能取消正在进行的请求?如果是的话怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!