How to change body in OkHttp Response? How to change body in OkHttp Response? android android

How to change body in OkHttp Response?


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.


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


As a minor change I wouldn't use the string() method cause it can be called only once on this request. You do use the response.newBuilder() so other interceptors down the chain will be able to call string() on your new one but I found myself wasting a couple of hours because I was actually calling it twice :P.

So i suggest something like the following

BufferedSource source = response.body().source();source.request(Long.MAX_VALUE); // Buffer the entire body.Buffer buffer = source.buffer();String responseBodyString = buffer.clone().readString(Charset.forName("UTF-8"));