Why we use Callback response in enqueue method of OKhttp in android

1.2k views Asked by At

I just made a simple JSON parsing program with Okhttp now what is Callback in Response of OKhttp and Why we use this ?

OkHttpClient okHttpClient=new OkHttpClient();

    Request request=new Request.Builder().url(url).build();

  okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

        }
    });
2

There are 2 answers

0
rushabhshah1693 On BEST ANSWER
  • Callbacks are used for asynchronous calls, in this case it will either return you the result from your network call to the url(Json/Xml data) in onsuccess or if there is an error onfailure will be called.

  • Error could be if connection didn't got through or connection timeout, response timeout, resource/address not valid, etc.

0
Jasper7 On

You have used enqueue, this has placed the request into a Queue along with any others. Its the same as dobackground, takes it off the Mainthread and allows other actions to continue

The Callback, is required so that when there is a response from the Website, it knows which request was used and passes the data back via the Callback.

https://square.github.io/okhttp/3.x/okhttp/okhttp3/Callback.html