Retrofit與okhttp共同出自于Square公司,retrofit就是對okhttp做了一層封裝。把網絡請求都交給給了Okhttp,我們只需要通過簡單的配置就能使用retrofit來進行網絡請求了,其主要作者是Android大神JakeWharton。
導包:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依賴包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'//ConverterFactory的String依賴包
*這里需要值得注意的是導入的retrofit2包的版本必須要一致,否則就會報錯。
首先定義我們請求的Api,我們假設是這樣的
http://106.3.227.33/pulamsi/mobileLogin/submit.html
與Okhttp不同的是,Retrofit需要定義一個接口,用來返回我們的Call對象,這里示范的是Post請求:
public interfaceRequestServes {
@POST("mobileLogin/submit.html")
CallgetString(@Query("loginname") String loginname,@Query("nloginpwd") String nloginpwd);
}
Retrofit提供的請求方式注解有@GET和@POST,參數注解有@PATH和@Query等,我們只介紹常用的;前兩個顧名思義就是定義你的請求方式Get or Post,后面的@PATH指的是通過參數填充完整的路徑,一般用法:
@GET("{name}")
CallgetUser(@Path("name")String name);
這里的參數username會被填充至{name}中,形成完整的Url請求地址,{name}相當于一個占位符;
@Query就是我們的請求的鍵值對的設置,我們構建Call對象的時候會傳入此參數,
123
@POST("mobileLogin/submit.html")
CallgetString(@Query("loginname")String loginname,@Query("nloginpwd")String nloginpwd);
這里@Query("loginname")就是鍵,后面的loginname就是具體的值了,值得注意的是Get和Post請求,都是這樣填充參數的;
接口寫完了之后我們需要來定義Retrofit對象來進行請求了;
創建一個Retrofit 對象
Retrofit retrofit =newRetrofit.Builder().
baseUrl("http://106.3.227.33/pulamsi/")????????????????????//增加返回值為String的持
.addConverterFactory(ScalarsConverterFactory.create())????//增加返回值為Gson的支持(以實體類返回)
.addConverterFactory(GsonConverterFactory.create())????????//增加返回值為Oservable的支持
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
這里的baseUrl加上之前@POST("mobileLogin/submit.html")定義的參數形成完整的請求地址;
addConverterFactory(ScalarsConverterFactory.create())的意思是構建了一個返回支持,如果你的Call對象的泛型接收另外的格式需要添加另外的支持,上述代碼已經列出;
接下來我們用這個Retrofit對象創建一個RequestSerives接口對象,也就是我們之前定義的那個接口,并且得到我們的Call對象;
RequestSerives requestSerives = retrofit.create(RequestSerives.class);//這里采用的是Java的動態代理模式Call call = requestSerives.getString("userName","1234");//傳入我們請求的鍵值對的值
利用得到的Call對象,然后我們就發出網絡請求了:
call.enqueue(newCallback() {
@OverridepublicvoidonResponse(Call call, Response response){
Log.e("===","return:"response.body().toString());
}@OverridepublicvoidonFailure(Call call, Throwable t){
Log.e("===","失敗");
}});