關於Retrofit網路請求URL中含有可變引數的處理
開題:在此預設各位看官對Retrofit、以及Okhttp已經有過一定的瞭解及應用,所以今天我們不談基礎入門的東西,今天我們談在Retrofit請求介面管理類中URL引數含有動態引數的處理方式。一般我們使用Retrofit大部分場景中URL都是以註解的方式靜態宣告的,即URL及path路徑都是固定不變,可變部分作為方法的引數傳入,那有一些特殊情況會要求我們再使用@GET()、或者@POST()的時候URL路徑裡含有可變引數,需要動態處理,下面通過例子我逐個為大家分析講解。
說明:以下所有Retrofit請求的BaseURL為https://192.168.1.101/api/,介面地址為本地測試,不程式碼以下介面真實可用
1.GET請求
1.)普通get請求
https://192.168.1.101/api/MovieList
@GET("MovieList")
Observable<ResultEntity<MovieEntity>> getMovieList();
2.) url中含有引數
https://192.168.1.101/api/MovieList/2018
分析:2018為動態可變部分,代表指定idMovie,api/MovieList/{movieId}
@GET("MovieList{movieId}") Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId );
或者
https://192.168.1.101/api/MovieList/2018/comedy
分析:請求指定年下型別為comedy的電影,可變部分為年份/型別 請求地址可變部分歸類為 api/{movieId}/{type}
@GET("MovieList{movieId}/{type}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId ,@Path("type") String type);
3.)可變引數在URL的問號之後
https://192.168.1.101/api/MovieList?movieId=10011
分析:問號之後的引數可以直接用@Query註解在作為方法引數傳入
@GET("MovieList")
Observable<ResultEntity<MovieEntity>> getMovieList(@Query("movieId") String movieId);
4.) 問號後面有多個引數 :
https://192.168.1.101/api/MovieList?movieId=10011&type=3
@GET("MovieList")
Observable<ResultEntity<MovieEntity>> getMovieList(@Query("movieId") String movieId,@Query("type") int type);
5.)問號後面有多個引數,且引數個數不定
https://192.168.1.101/api/MovieList?movieId=10011&type=4&year=2013&......
分析:作為Get請求,後面引數根據具體業務確定引數多少,也就是引數個數可變,但不確定多少個,可以藉助@Querymap
@GET("MovieList")
Observable<ResultEntity<MovieEntity>> getMovieList(@QueryMap Map<String ,Object> map);
2.POST請求
1.) url中含有可變引數,post的資料只有一個type
https://192.168.1.101/api/MovieList/2018
分析:url中2018為可變內容,post需要提交的引數只有一個type,2018可動態改變
@FormUrlEncoded
@POST("MovieList/{movieId}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId, @Field("type") String type);
2.) url中含有可變引數、問號之後需要加入token,post的資料只有一個type
https://192.168.1.101/api/MovieList/2018?token=4654551321563132fasd5645ds3
@FormUrlEncoded
@POST("MovieList/{movieId}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId,
@Query("token") String token,
@Field("type") String type);
3.) url中含有可變引數、問號之後需要加入token,post的資料為一個物件(json串)
https://192.168.1.101/api/MovieList/2018?token=4654551321563132fasd5645ds3
@POST("MovieList/{movieId}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId,
@Query("token") String token,
@Body MovieEntity entity);