How to change body in OkHttp Response?

Below is Response Intercepter class where you can intercept okkhttp responce and add your own response. and send it to retrofit.

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class ApiResponseInterceptor implements Interceptor {

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        okhttp3.Response response = chain.proceed(request);
        if(response.code() == 200) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("code",200);
                jsonObject.put("status","OK");
                jsonObject.put("message","Successful");

                MediaType contentType = response.body().contentType();
                ResponseBody body = ResponseBody.create(contentType, jsonObject.toString());
                return response.newBuilder().body(body).build();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if(response.code() == 403) {

        }
        return response;
    }
}

Yow will get your modified response here in your retrofit callback

call.enqueue(new Callback<EventResponce>() {
            @Override
            public void onResponse(Call<EventResponce> call, Response<EventResponce> response) {
                // you will get your own modified responce here
            }

            @Override
            public void onFailure(Call<EventResponce> call, Throwable t) {

            }
        });

Add this

MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject);
return response.newBuilder().body(body).build();

after your response modification. jsonObject is the modified JSON you want to return.