關于Retrofit的學習,我算是比較晚的了,而現在Retrofit已經是Android非常流行的網絡請求框架了。之前,我沒有學過Retrofit,但最近公司的新項目使用了Retrofit、Rxjava和OkHttp來進行封裝,使用起來非常簡便,增加代碼的美觀程度,也降低了耦合度,這是一個非常棒的框架,特別是這三者一起使用。
簡介
Retrofit是Square公司開發的一款針對Android網絡請求的框架,現在已經更新到2.3版本了。Retrofit的最大特點是使用運行時注解的方式提供功能。
Retrofit的使用
關于Retrofit的使用,其實還是很簡單的,而且邏輯思路也比較清晰,所以開發者是很容易上手的。
添加依賴
build.gradle文件的dependencies下添加以下依賴:
上面除了添加Retrofit依賴,還添加了gson依賴,來解析請求得到的json數據。
定義使用的數據集合
class Result <T>{ var status: Int? = -1//請求結果 lateinit var message: String; var content :T?= null}這是返回結果的集合,使用了kotlin來寫
class Content { var name: String?= null var mobile :String?= null var address :String?= null}需要的內容集合類
請求
需要一個接口,并且編寫請求的方法
interface HttpService { @GET("index.php?m=Api&c=User&a=userInfo") fun getUserInfo(): Call<Result<Content>>}調用請求
private void request() { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://one.sinalwj.cn//") .addConverterFactory(GsonConverterFactory.create()) .build(); HttpService service = retrofit.create(HttpService.class); Call<Result<Content>> call = service.getUserInfo(); call.enqueue(new Callback<Result<Content>>() { @Override public void onResponse(Call<Result<Content>> call, Response<Result<Content>> response) { Log.i("tag", response.body().getContent().getName()); } @Override public void onFailure(Call<Result<Content>> call, Throwable t) { Log.i("tag", "失敗"); } }); }以上就是Retrofit的get請求方式。GET請求需要在請求方法之前添加一個GET注解來標明這是一個GET請求,同樣,如果是POST請求需要一個POST注解。

@POST
POST請求,需要添加一個@POST的注解,并且需要還需要使用@FormUrlEncoded 注解來表明,這是一個表單,使用@Field注解,傳入表單需要的參數。
@FormUrlEncoded //表單 @POST("index.php?m=Api&c=User&a=userInfo") fun getUserInfo( @Field("user_id") user_id: String //參數 ): Observable<BaseResult<User>> //返回數據類型@Body
@Body注解是針對POST的請求方式,如傳輸數據JSON格式
class Content { var name: String?= null lateinit var sn:SN class SN{ var out :String ?= null var errNo :Int ?= -1 }}@GET("ajax.php")fun getInfo(@Body content: Content): Call<Result<Content>>@Path
使用@Path可以動態的配置URL地址。
@GET("{path/}{index.php?m=Api&c=User&a=userInfo")fun getUserInfo(@Path("path")path: String): Call<Result<Content>>@Query
@Query即動態指定查詢條件
@GET("ajax.php")fun getInfo(@Query("id")id: String): Call<Result<Content>>@Query是查詢單一的條件,但是如果是多個條件的話,就不適用了,那么就需要用到@QueryMap注解。@QueryMap就是動態指定查詢條件組。
文件上傳
使用@Part注解來表示單個文件上傳,而@PartMap注解跟單文件上傳是類似的,是不過是使用了Map集合來封裝了上傳的文件,即多文件上傳。
除了以上的注解,還有@Header,即表示加入消息報頭,因為在http請求的時候,為了防止攻擊、過濾不安全的訪問和添加特殊加密的訪問來保證安全,需要在消息報頭中攜帶一些特殊的消息處理,而在Retrofix中使用@Header即可實現添加消息報頭。
從上面的Retrofix實踐和注解的講解中,我們知道使用Retrofix可以很簡單的,而且代碼邏輯比較清晰的做http請求,其提供非常多的注解來給開發者使用,簡化了代碼。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答