view raw
Nick Unuchek Nick Unuchek - 6 months ago 67
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?


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.