TrinityTuts Tips

Cancel current or queue request in OKHTTP3

This tip is small but very useful if you are working with OKHTTP3 library. With the help of this code, you can cancel current or queue request of OkHTTP 3.

OkHttpClient client = new OkHttpClient();
        MediaType MEDIA_TYPE = MediaType.parse("application/json");
        JSONObject postData = new JSONObject();
        try {
            postData.put("q", "My Query");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());

        Request request = new Request.Builder()
                .url(Urls.search)
                .post(body)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .tag("preRequest")
                .build();

       // Cancel queue request 
        for (Call call : client.dispatcher().queuedCalls()) {
            if (call.request().tag().equals("requestKey"))
                call.cancel();
        }

      // Cancel last request 
        for (Call call : client.dispatcher().runningCalls()) {
            if (call.request().tag().equals("preRequest")) {
                Log.e("cancle", "requestCancel");
                call.cancel();
            }
        }

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                call.cancel();
            }

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

                final String mMessage = response.body().string();

                Search.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            /** Your response **/
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
  

Hope this small piece of code help you.