現在市面上已經有了很多關于Retrofit的使用教程的博文,本篇只是我自己學習使用Retrofit時候的一個總結。本文參考自:霍丙乾 騰訊Bugly的《深入淺出 Retrofit,這么牛逼的框架你們還不來看看?》一文。
附:Retrofit首頁及官方教程
使用首先要導入Retrofit的依賴:
//這兩個依賴庫的版本必須要保持一致compile 'com.squareup.retrofit2:retrofit:2.1.0'//Retrofit依賴compile 'com.squareup.retrofit2:converter-gson:2.1.0'//Retrofit數據轉換的依賴,可以直接將json轉化為實體類在新建項目并建立依賴之后就可以開始使用Retrofit了。
這里使用聚合數據提供的接口來獲取數據:
請求地址:http://op.juhe.cn/onebox/weather/query 請求參數:cityname=%E5%8C%97%E4%BA%AC&dtype=json&key=19f4708ebed559eac920bbaa51b24a12 請求方式:GET
package com.wei.retrofitdemo.Interface;import com.wei.retrofitdemo.javaBean.WeatherInform;import retrofit2.Call;import retrofit2.http.GET;import retrofit2.http.Query;/** * Created by WQC on 2016/7/15. */public interface WeatherService { //用于指定請求的方式 @GET("weather/query") //具體的請求回調的方法,可以使用@Query注解來添加url中的參數 Call<WeatherInform> getWeather(@Query("cityname") String cityname, @Query("dtype") String dtype, @Query("key") String key);}這里邊用到了WeatherInform這個JavaBean,可以使用AS的GsonFormat將json數據轉換成對應的Java類:
(因為json轉成的Java類太長,放在文件中供下載查看) WeatherInform.java類下載地址
Url的配置方式有多種,而且這些方式可以混合使用,但是最好只用一種,不然會頭暈的。
path 是絕對路徑的形式: path = “/path”,baseUrl = “URL:http://host:port/a/b” Url = “URL:http://host:port/path”
path 是相對路徑,baseUrl 是目錄形式: path = “path”,baseUrl = “URL:http://host:port/a/b/” Url = “URL:http://host:port/a/b/path”
path 是相對路徑,baseUrl 是文件形式: path = “path”,baseUrl = “URL:http://host:port/a/b” Url = “URL:http://host:port/a/path”
path 是完整的 Url: path = “http://host:port/aa/path“,baseUrl = “http://host:port/a/b” Url = “http://host:port/aa/path”
以本文使用的URL為例(使用的是第二種方式):
path : “weather/query” baseUrl:”http://op.juhe.cn/onebox/”
所以最終的Url就是:“http://op.juhe.cn/onebox/weather/query“
1. 異步:
mWeatherCall = mWeatherService.getWeather("北京","json","19f4708ebed559eac920bbaa51b24a12"); mWeatherCall.enqueue(new Callback<WeatherInform>() { @Override public void onResponse(Call<WeatherInform> call, Response<WeatherInform> response) { if (response != null) { WeatherInform weatherInform = response.body(); if (weatherInform != null) { Log.i(TAG, "onResponse: " + weatherInform.getReason()); } }else{ Log.i(TAG, "onResponse: response is null"); } } @Override public void onFailure(Call<WeatherInform> call, Throwable t) { Log.i(TAG, "onFailure: "); } });2. 同步
try { Response<WeatherInform> weatherInform = mWeatherCall.execute(); } catch (IOException e) { e.PRintStackTrace(); }以上就是Retrofit的簡單使用方法,他使用okhttp作為底層網絡請求方式,在上層進行封裝,使用注解的方式來使用。Retrofit還可以配合RxJava,RxAndroid來使用,提供更加簡潔的網絡請求方式。
新聞熱點
疑難解答