文章出處
文章列表
Retrofit模型簡介
- POJO或模型實體類 : 從服務器獲取的JSON數據將被填充到這種類的實例中。
- 接口 : 我們需要創建一個接口來管理像GET,POST...等請求的URL,這是一個服務類。
- RestAdapter類 : 這是一個REST客戶端(RestClient)類,retrofit中默認用的是Gson來解析JSON數據,你也可以設置自己的JSON解析器。
使用
添加依賴
compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2'
添加權限
<uses-permission android:name="android.permission.INTERNET"/>
- 創建實體類
- 使用GsonFormat創建實體類,這里就不詳細說了。
創建Retrofit對象
//1.創建一個Retrofit對象 Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create())//解析方法 .baseUrl("http://api.m.mtime.cn/PageSubArea/TrailerList.api/") .build();
聲明接口
//2.聲明一個接口 public interface IItemService{ /** * 根據movieId獲取對應的信息數據 * @param movieId * @return */ @GET("Item/{movieId}") Call<Item> getItem(@Path("movieId") String movieId); }
創建訪問API請求
IItemService service = retrofit.create(IItemService.class); Call<Item> call = service.getItem("65094");
- 調用
同步調用
Item bean = call.execute();
異步調用
call.enqueue(new Callback<Item>() { @Override public void onResponse(Call<Item> call, Response<Item> response) { Item bean = response.body(); Log.i("輸出", bean.toString()); } @Override public void onFailure(Call<Item> call, Throwable t) { Log.i("輸出",t.toString()); } });
取消請求
call.cancel();
文章列表
全站熱搜