2

I am not so familiar with OkHttp library and I have some doubts on how it should be used for async requests.

For Android programming, I was using the android library for http and I was using asyncTask for some request.

But since I wanted to try OkHttp library, I faced some "problem" on what is the correct way it should be used.

EXAMPLE:

Imagine you want to implement async request using OkHttp. I read that OkHttp have it's own async api ( https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java ).

But then I came across this post (Square`s OkHttp. Download progress) in which the guy used the "old" asyncTask but with OkHttp request ( I also found on other forums that people are using AsyncTask with OkHttp).

This confused be a bit cause it could be made simply with this piece of code, which can be also adapted for POST:

OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
        .url("http://google.com")
        .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        Log.e(LOG_TAG, e.toString());
    }

    @Override
    public void onResponse(Response response) throws IOException {
        Log.w(LOG_TAG, response.body().string());
        Log.i(LOG_TAG, response.toString());
    }
});

QUESTION:

  1. what is the correct way to use async requests with OkHttp?
  2. is it a good practice to use AsyncTask with OkHTTP?
  3. in which cases should I use AsyncTask with OkHttp instead of using OkHttp async api?
Community
  • 1
  • 1
lucidBug
  • 197
  • 1
  • 10

1 Answers1

1

I tried both approaches, and both of them are working for my need. This really depends on your situation, and what you really need. The asynctask version is nicer, looks easier , but the other one (also if you do it with retrofit) offers some more functionalities.

e.g. In asyncTask there is no possibility to cancel a network call, which with retrofit (I refer to retrofit cause I tried with this solution) can be done easily.

Here are some good links to give you a better idea how retrofit works :

https://futurestud.io/blog/retrofit-2-upgrade-guide-from-1-9

http://instructure.github.io/blog/2013/12/09/volley-vs-retrofit/

Also AsyncTask is actually sync call (this also depends on the AsyncTask version). So for async call, you need to use other approach.

lucidBug
  • 197
  • 1
  • 10