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?
OkHttp Response To implement our JSON decoder, we need to extract the JSON from the result of the service call. For this, we can access the body via the body() method of the Response object.
Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks.
OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With