Android Retrofit框架的使用
Retrofit是Square開源的一款基于OkHttp(也是他家的)封裝的網絡請求框架,主要的網絡請求還是OkHttp來完成,Retrofit只是對OkHttp進行了封裝,可以讓我們更加簡單方便的使用,目前大部分公司都在使用這款框架,Retrofit的原理也是面試必問的問題之一了,所以我們不僅要會使用,也要對其實現原理有一個大概的了解。
本片文章從使用角度來說,不對的地方希望大家在評論區交流,我會及時改進,共同進步,文章中的demo可以從github下載。
Retrofit優點Retrofit的大部分配置是通過注解來實現的,配置簡單,使用方便;支持多種返回類型包括RxJava和協程,可以配置不同的解析器來進行數據解析,如Json,xml等
Retrofit的使用以下代碼全部為Kotlin語言編寫,畢竟現在Kotlin也是大勢所趨了。
1.引入依賴項github地址:github.com/square/retr…
implementation ’com.squareup.retrofit2:retrofit:2.9.0’//支持Gson解析json數據implementation ’com.squareup.retrofit2:converter-gson:2.9.0’//支持RxJava返回類型implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'//支持協程,Retrofit2.6.0及以上版本不需要引入,Retrofit內置已經支持//implementation ’com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2’2.添加網絡權限
<uses-permission android:name='android.permission.INTERNET'/>3.編寫Retrofit輔助類
首先定義一個RetrofitHelper輔助類,編寫Retrofit單例,Retrofit內部已經維護了線程池做網絡請求,不需要創建多個
注:BASE_URL必須為 '/' 結尾
object RetrofitHelper { //baseUrl根據自己項目修改 private const val BASE_URL = 'https://www.baidu.com' private var retrofit: Retrofit? = null private var retrofitBuilder: Retrofit.Builder? = null //Retrofit初始化 fun init(){ if (retrofitBuilder == null) { val client = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .build() retrofitBuilder = Retrofit.Builder() .baseUrl(BASE_URL) //支持Json數據解析 .addConverterFactory(GsonConverterFactory.create()) //支持RxJava返回類型 .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) } retrofit = retrofitBuilder!!.build() } fun getRetrofit():Retrofit{ if (retrofit == null) { throw IllegalAccessException('Retrofit is not initialized!') } return retrofit!! }}
然后再Application中進行初始化
class App:Application() { override fun onCreate() { super.onCreate() RetrofitHelper.init() }}
在Manifest文件中指定Application
<application android:name='.App' android:allowBackup='true' android:icon='@mipmap/ic_launcher' android:label='@string/app_name' android:roundIcon='@mipmap/ic_launcher_round' android:supportsRtl='true' android:networkSecurityConfig='@xml/network_security_config' android:theme='@style/Theme.RetrofitDemo'> <activity android:name='.MainActivity'> <intent-filter> <action android:name='android.intent.action.MAIN' /> <category android:name='android.intent.category.LAUNCHER' /> </intent-filter> </activity></application>
Android P系統限制了明文流量的網絡請求 解決的辦法有2種 1.把所有的http請求全部改為https請求 2.在res的xml目錄(),然后創建一個名為:network_security_config.xml文件
<?xml version='1.0' encoding='utf-8'?><network-security-config><base-config cleartextTrafficPermitted='true' /></network-security-config>4.定義ApiService
首先我們先用一個最簡單的GET請求來試一下,這個接口是請求天氣情況的,免費的
interface Api { @GET('http://www.weather.com.cn/data/sk/{cityCode}.html') fun getWeather(@Path('cityCode')code:String):Observable<WeatherInfo>}
定義返回類型,為了方便打印,用的data class 類型
data class WeatherInfo( var weatherinfo:Info?=null) { data class Info( var city:String?, var cityid:String?, var temp:String?, var WD:String?, var WS:String?, var SD:String?, var AP:String?, var njd:String?, var WSE:String?, var time:String?)}
首先用@GET注解表示該借口為get請求,GET注解的value為請求地址,完整的請求地址為baseUrl+value,如value為完整地址,則會使用value為請求地址,一般通用情況下baseUrl = 'www.weather.com.cn/', 然后GET('data/sk/{cityCode}.html') @Path是網址中的參數,用來替換。
5.實現接口方法5.1RxJava方法實現
class RetrofitViewModel:ViewModel() { private val disposables:CompositeDisposable by lazy { CompositeDisposable() } fun addDisposable(d:Disposable){ disposables.add(d) } val weatherLiveData = MutableLiveData<WeatherInfo>() fun getWeather(){ RetrofitHelper.getRetrofit().create(Api::class.java).getWeather('101010100') .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object :Observer<WeatherInfo>{ override fun onComplete() {} override fun onSubscribe(d: Disposable) { addDisposable(d) } override fun onNext(t: WeatherInfo) { weatherLiveData.value = t } override fun onError(e: Throwable) { } }) } override fun onCleared() { super.onCleared() disposables.clear() }}
這里是用ViewModel中做的操作,如果是MVP模式放在Presenter中進行就好,首先通過Retrofit單例調用Service的對象的getWeather方法,指定上下游事件的線程,創建觀察者對象進行監聽,在onNext方法中拿到返回結果后回調給Activity,數據回調用的是LiveData,在Activity中操作如下
class MainActivity : AppCompatActivity() { private val viewModel by viewModels<RetrofitViewModel>() private var btnWeather: Button? = null private var tvWeather: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel.weatherLiveData.observe(this, Observer { tvWeather?.text = it.toString()) }) btnWeather = findViewById<Button>(R.id.btnWeather) tvWeather = findViewById(R.id.tvWeather) btnWeather?.setOnClickListener { viewModel.getWeather() } }}
在Activity中
1.創建ViewModel對象
2.注冊LiveData的回調
3.獲取天氣情況
如下圖所示
github地址:github.com/ZhiLiangT/R…
以上就是Android Retrofit框架的使用的詳細內容,更多關于Android Retrofit框架的資料請關注好吧啦網其它相關文章!
相關文章:
