浅谈Android Retrofit 添加头部的几种方式

方式一、直接在参数里写 每次访问的时候都要传入一下

@GET("weatherservice/citylist") 
Observable request(@Header("apikey") String apikey,@Query("cityname") String cityname);

方式二、写到注解里这样就少了个参数,但是每定义个接口都要写一次也是比较麻烦

@Headers("apikey:ac7c302dc489a69082cbee6a89e3646c") 
@GET("weatherservice/cityid") request query(@Query("cityid")String cityid); 

方式三、在创建Retrofit的时候添加,最方便的方式

OkHttpClient client = new OkHttpClient.Builder()
 .addInterceptor(new Interceptor() { 
@Override 
public Response intercept(Chain chain) throws IOException { 
Request request = chain.request(); 
Request.Builder builder1 = request.newBuilder(); 
Request build = builder1.addHeader("apikey", "ac7c302dc489a69082cbee6********").build(); 
return chain.proceed(build); } })
.retryOnConnectionFailure(true)
 .build();
 mRetrofit = new Retrofit.Builder()
 .client(client)
 .baseUrl(ConstantApi.url) 
.addCallAdapterFactory(...

Android技术交流群:633600411

你可能感兴趣的:(浅谈Android Retrofit 添加头部的几种方式)