Nick Unuchek Nick Unuchek - 1 month ago 22
Android Question

How to change body in OkHttp Response?

I'm using retrofit. To catch response i'm using Interceptor:

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(myinterceptor);


here is code of interceptor:
new Interceptor() {

@Override
public Response intercept(Chain chain) throws IOException {

Request request = chain.request();
Response response = chain.proceed(request);
if (path.equals("/user")){
String stringJson = response.body().string();
JSONObject jsonObject = new JSONObject(stringJson);
jsonObject.put("key",1);
//here I need to set this new json to response and then return this response


How to change body in OkHttp Response?

Answer

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.