• Retrofit2.0+OkHttp设置统一的请求头(request headers)


    有时候要求Retrofit2的接口中每个都要增加上headers,又不想做重复的事情,可以使用这种方法来为每个request请求都设置上相同的请求头header。

    修改请求头request headers主要是通过拦截器来实现,下面是我自己根据需要设置的。如果还有增加其他的header,可以再进行增加。

    1. /**
    2. * 请求拦截器,修改请求header
    3. */
    4. private class RequestInterceptor implements Interceptor{
    5.  
    6. @Override
    7. public Response intercept(Chain chain) throws IOException {
    8. Request request = chain.request()
    9. .newBuilder()
    10. .addHeader("Content-Type", "text/html; charset=UTF-8")
    11. // .addHeader("Accept-Encoding", "*")
    12. .addHeader("Connection", "keep-alive")
    13. .addHeader("Accept", "*/*")
    14. .addHeader("Access-Control-Allow-Origin", "*")
    15. .addHeader("Access-Control-Allow-Headers", "X-Requested-With")
    16. .addHeader("Vary", "Accept-Encoding")
    17. // .addHeader("Cookie", "add cookies here")
    18. .build();
    19.  
    20. Log.v("zcb", "request:" + request.toString());
    21. Log.v("zcb", "request headers:" + request.headers().toString());
    22.  
    23. return chain.proceed(request);
    24. }
    25. }

    使用方法:

    1. private OkHttpClient getOkHttpClient() {
    2. //定制OkHttp
    3. OkHttpClient.Builder httpClientBuilder = new OkHttpClient
    4. .Builder();
    5. //设置超时时间
    6. httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    7. httpClientBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    8. httpClientBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    9. //使用拦截器
    10. httpClientBuilder.addInterceptor(new RequestInterceptor());
    11. httpClientBuilder.addInterceptor(new LogInterceptor());
    12. return httpClientBuilder.build();
    13. }
  • 相关阅读:
    foreach
    if
    注意事项
    Maven测试
    课程评价
    个人总结
    HTML表格CSS美化
    让多个输入框对齐
    CSS样式写在JSP代码中的几种方法
    日常
  • 原文地址:https://www.cnblogs.com/onetwo/p/7278116.html
Copyright © 2020-2023  润新知