简体   繁体   English

Okhttp:异步请求不会在 onResponse 后立即停止

[英]Okhttp : Asynchronous request doesn't stop immediately after onResponse

First sorry for my English which is not my native language.首先抱歉我的英语不是我的母语。

I use okhttp to do some simple asynchronous calls but my program doesn't stop immediately after the call of onResponse.我使用 okhttp 进行一些简单的异步调用,但我的程序在调用 onResponse 后不会立即停止。 It takes some seconds and then stops.需要几秒钟,然后停止。 I don't have this issue on Android 5 but on my desktop.我在 Android 5 上没有这个问题,但在我的桌面上。 I have the same issue with others URLs.我对其他 URL 也有同样的问题。 Maybe there is something I did wrong.也许我做错了什么。 The request is performed in another thread.请求在另一个线程中执行。 My network is under a proxy.我的网络在代理下。

I use : okhttp-2.4.0 and okio-1.4.0 and java8 .我使用: okhttp-2.4.0okio-1.4.0java8

Redirect me if this issue was already answered.如果此问题已得到解答,请重定向我。

This my code : `这是我的代码:`

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {

    Settings.setProxy();
    Request request = new Request.Builder()
            .url("http://openlibrary.org/search.json?q=la+famille")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            System.out.println("error");
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println(response.body().string());
            System.out.println("coucou");
        }
    });
}

` `

As you find out from the issue when you do an async call an ExecutorService is created and the pool is keeping the VM alive.正如您从执行异步调用时的问题中发现的那样,会创建 ExecutorService 并且池使 VM 保持活动状态。

To shutdown the pool just get the dispatcher and close it:要关闭池,只需获取调度程序并关闭它:

client.getDispatcher().getExecutorService().shutdown();

我不知道如何,但这条线对我client.connectionPool().evictAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM