How to change body in OkHttp Response?

前端 未结 5 2020
清酒与你
清酒与你 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:37

    As a minor change I wouldn't use the string() method cause it can be called only once on this request. You do use the response.newBuilder() so other interceptors down the chain will be able to call string() on your new one but I found myself wasting a couple of hours because I was actually calling it twice :P.

    So i suggest something like the following

    BufferedSource source = response.body().source();
    source.request(Long.MAX_VALUE); // Buffer the entire body.
    Buffer buffer = source.buffer();
    String responseBodyString = buffer.clone().readString(Charset.forName("UTF-8"));
    

提交回复
热议问题