How to change body in OkHttp Response?

前端 未结 5 2023
清酒与你
清酒与你 2021-02-01 06:05

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

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


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 06:40

    Here's a tight, complete example of adding an interceptor that modifies JSON to an OkHttpClient. It uses GSON to manage the JSON.

            client.addInterceptor(chain -> {
                final Request request = chain.request();
                final String path = request.url().uri().getPath();
                final Response response = chain.proceed(request);
    
                String body = response.body().string();
                final JsonElement element = new JsonParser().parse(body);
                if ("/the/endpoint/you/want/to/modify".equals(path)){
                    final JsonObject object = element.getAsJsonObject();
                    // v v v v v v All this for these lines v v v v v v v
                    object.addProperty("some_json_name","some_json_value");
                    object.addProperty("existing_property","updated_value");
                    object.addProperty("numbers_work_too",1.2);
                    // ^ ^ ^ ^ ^ ^ All this for these lines ^ ^ ^ ^ ^ ^ ^
                    body = object.toString();
                }
                return response.newBuilder().body(ResponseBody.create(response.body().contentType(), body)).build();
            });
    

提交回复
热议问题