Nick Unuchek Nick Unuchek - 1 year ago 216
Android Question

How to change body in OkHttp Response?

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

OkHttpClient okHttpClient = new OkHttpClient();

here is code of interceptor:
new Interceptor() {

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);
//here I need to set this new json to response and then return this response

How to change body in OkHttp Response?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download