Retrofit添加 Interceptor

User-Agent

public class UAInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("User-Agent","Android;lovelycn;1.0");
        return chain.proceed(builder.build());
    }
}

log日志打印

public class LogInterceptor implements Interceptor {

    public String TAG = "okHttp";

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Log.e(TAG, "\n");
        Log.e(TAG, "----------Start----------------");
        Log.e(TAG, "| " + request.toString());
        String method = request.method();
        if ("POST".equals(method)) {
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
                Log.e(TAG, "| RequestParams:{" + sb.toString() + "}");
            }
        }
        Log.e(TAG, "| Response:" + content);
        Log.e(TAG, "----------End:" + duration + "毫秒----------");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }
}
  public static OkHttpClient genericClient() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new UAInterceptor())
                .addInterceptor(new LogInterceptor())
                .build();
        return httpClient;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 我的金錢花在哪些方面是讓我感覺最好的? 1、花在提升自己值得感和配得感的方面,比如買漂亮衣服和化妝品 2、花在健康...
    慶清閱讀 142評(píng)論 0 0
  • iOS的模糊效果實(shí)現(xiàn)方法有好幾種,基本分為兩種方式,一種是將圖片進(jìn)行模糊,一種是將模糊的控件放在UI界面上,使控件...
    owen_10閱讀 26,591評(píng)論 18 98
  • 傍晚,打開臺(tái)燈,燈罩亞麻的紋理清晰可見。突發(fā)奇想,拿來秋天采的蘆葦,用手機(jī)拍了一組照片。 燈影里的蘆葦,頗有禪意~
    綺夢(mèng)識(shí)君閱讀 382評(píng)論 4 7

友情鏈接更多精彩內(nèi)容