Okhttp: async request doesn't stop immediately after onResponse

First, sorry about my english which is not my native language.

I am using okhttp to make simple asynchronous calls, but my program doesn't stop immediately after the onResponse is called. It takes a few seconds and then stops. I don't have this problem on Android 5, but on my desktop. I have the same problem with other urls. Maybe I did something wrong. The request is being executed on a different thread. My network is under a proxy.

I am using: okhttp-2.4.0

and okio-1.4.0

and java8

.

Please refer me if this issue has already been answered.

This code of mine: `

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

      

`

+3


source to share


1 answer


As you learned from the problem, when you make an asynchronous call, an ExecutorService is created and the pool keeps the VM alive.

To shutdown the pool, just get the dispatcher and close it:



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

      

+2


source







All Articles