美文网首页Android
Retrofit2.0添加Header的方法总结

Retrofit2.0添加Header的方法总结

作者: duyi324 | 来源:发表于2018-08-17 19:49 被阅读0次

    一、使用注解

    1. 添加单个header

    public interface ApiService {  
        @Headers("Content-Type: application/javascript")
        @GET("/data")
        Call<List<Data>> getData();
    }
    

    2. 添加多个header

    public interface ApiService {  
        @Headers({
            "Content-Type: application/javascript",
            "User-Agent: YourAgent"
        })
        @GET("/data/{user_id}")
        Call<List<Data>> getData();
    }
    

    3. 动态添加header

    public interface ApiService {  
        @GET("/data")
        Call<List<Data>> getData(@Header("Content-Range") String contentRange);
    }
    

    二、如果要添加全局header,则需要在代码中添加header

    OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request()
                                    .newBuilder()
                                    .addHeader("X-Requested-With", "XMLHttpRequest")
                                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36")
                                    .build();
                            return chain.proceed(request);
                        }
                    }).build();
    Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl(Constant.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
    
    

    相关文章

      网友评论

        本文标题:Retrofit2.0添加Header的方法总结

        本文链接:https://www.haomeiwen.com/subject/fcwtiftx.html