Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change body in OkHttp Response?

Tags:

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?

like image 665
NickUnuchek Avatar asked Mar 03 '16 13:03

NickUnuchek


People also ask

How do you get a response body from OkHttp?

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.

What is interceptor in OkHttp?

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.

What is the difference between retrofit and OkHttp?

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.


1 Answers

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.

like image 172
Rohit5k2 Avatar answered Oct 04 '22 17:10

Rohit5k2