怎么在Retrofit2.0中添加Header?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
(1)使用注解的方式添加一個header參數
public interface ApiService { @Headers("Cache-Control: max-age=560000") @GET("/data") Call<List<Data>> getData(); }
(2)使用注解的方式添加多個header參數
public interface ApiService { @Headers({ "Accept: application/vnd.yourapi.v1.full+json", "User-Agent: YourAppName" }) @GET("/data/{user_id}") Call<Data> getData(@Path("user_id") long userId); }
(3)使用注解的方式,header參數每次都不同,動態添加header
public interface ApiService { @GET("/data") Call<List<Data>> getData(@Header("Content-Range") String contentRange); }
(4)在代碼里添加header,需要使用攔截器
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); Request request = original.newBuilder() .header("User-Agent", "YourAppName") .header("Accept", "application/vnd.yourapi.v1.full+json") .method(original.method(), original.body()) .build(); return chain.proceed(request); } } OkHttpClient httpClient = client.build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient) .build();
看完上述內容,你們掌握怎么在Retrofit2.0中添加Header的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創新互聯行業資訊頻道,感謝各位的閱讀!
網頁標題:怎么在Retrofit2.0中添加Header-創新互聯
當前URL:http://vcdvsql.cn/article36/ddgcsg.html
成都網站建設公司_創新互聯,為您提供建站公司、網站收錄、品牌網站制作、用戶體驗、定制網站、面包屑導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯