Android Retrofit框架的使用
Retrofit介紹
Retrofit是Square開源的一款基于OkHttp(也是他家的)封裝的網(wǎng)絡(luò)請求框架,主要的網(wǎng)絡(luò)請求還是OkHttp來完成,Retrofit只是對OkHttp進行了封裝,可以讓我們更加簡單方便的使用,目前大部分公司都在使用這款框架,Retrofit的原理也是面試必問的問題之一了,所以我們不僅要會使用,也要對其實現(xiàn)原理有一個大概的了解。
本片文章從使用角度來說,不對的地方希望大家在評論區(qū)交流,我會及時改進,共同進步,文章中的demo可以從github下載。
Retrofit優(yōu)點
Retrofit的大部分配置是通過注解來實現(xiàn)的,配置簡單,使用方便;支持多種返回類型包括RxJava和協(xié)程,可以配置不同的解析器來進行數(shù)據(jù)解析,如Json,xml等
Retrofit的使用
以下代碼全部為Kotlin語言編寫,畢竟現(xiàn)在Kotlin也是大勢所趨了。
1.引入依賴項
github地址:github.com/square/retr…
implementation 'com.squareup.retrofit2:retrofit:2.9.0' //支持Gson解析json數(shù)據(jù) 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" //支持協(xié)程,Retrofit2.6.0及以上版本不需要引入,Retrofit內(nèi)置已經(jīng)支持 //implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
2.添加網(wǎng)絡(luò)權(quán)限
<uses-permission android:name="android.permission.INTERNET"/>
3.編寫Retrofit輔助類
首先定義一個RetrofitHelper輔助類,編寫Retrofit單例,Retrofit內(nèi)部已經(jīng)維護了線程池做網(wǎng)絡(luò)請求,不需要創(chuàng)建多個
注:BASE_URL必須為 "/" 結(jié)尾
object RetrofitHelper {
//baseUrl根據(jù)自己項目修改
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數(shù)據(jù)解析
.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系統(tǒng)限制了明文流量的網(wǎng)絡(luò)請求 解決的辦法有2種 1.把所有的http請求全部改為https請求 2.在res的xml目錄(),然后創(chuàng)建一個名為: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是網(wǎng)址中的參數(shù),用來替換。
5.實現(xiàn)接口方法
5.1RxJava方法實現(xiàn)
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單例調(diào)用Service的對象的getWeather方法,指定上下游事件的線程,創(chuàng)建觀察者對象進行監(jiān)聽,在onNext方法中拿到返回結(jié)果后回調(diào)給Activity,數(shù)據(jù)回調(diào)用的是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.創(chuàng)建ViewModel對象
2.注冊LiveData的回調(diào)
3.獲取天氣情況
如下圖所示

github地址:github.com/ZhiLiangT/R…
以上就是Android Retrofit框架的使用的詳細內(nèi)容,更多關(guān)于Android Retrofit框架的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
TextView使用SpannableString設(shè)置復(fù)合文本 SpannableString實現(xiàn)TextView的鏈接
這篇文章主要為大家詳細介紹了如何利用SpannableString實現(xiàn)TextView的鏈接效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
Android實戰(zhàn)教程第五篇之一鍵鎖屏應(yīng)用
這篇文章主要為大家詳細介紹了Android實戰(zhàn)教程第五篇之一鍵鎖屏應(yīng)用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
Android Studio使用USB真機調(diào)試詳解
這篇文章主要為大家詳細介紹了Android Studio使用USB真機調(diào)試的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
Flutter Http分塊下載與斷點續(xù)傳的實現(xiàn)
這篇文章主要介紹了Flutter Http分塊下載與斷點續(xù)傳的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
Android開發(fā)之使用SQLite存儲數(shù)據(jù)的方法分析
這篇文章主要介紹了Android開發(fā)之使用SQLite存儲數(shù)據(jù)的方法,結(jié)合實例形式分析了Android使用SQLite數(shù)據(jù)庫實現(xiàn)針對數(shù)據(jù)的增刪改查操作相關(guān)技巧,需要的朋友可以參考下2017-07-07
Android Studio綁定下拉框數(shù)據(jù)詳解
這篇文章主要為大家詳細介紹了Android Studio綁定下拉框數(shù)據(jù),Android Studio綁定網(wǎng)絡(luò)JSON數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
Android Studio EditText點擊圖標清除文本內(nèi)容的實例解析
這篇文章主要介紹了Android Studio EditText點擊圖標清除文本內(nèi)容的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-11-11
Android自定義view實現(xiàn)太極效果實例代碼
這篇文章主要介紹了Android自定義view實現(xiàn)太極效果實例代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05
Android?無障礙服務(wù)?performAction?調(diào)用過程分析
這篇文章主要介紹了Android?無障礙服務(wù)?performAction?調(diào)用過程分析,無障礙服務(wù)可以模擬一些用戶操作,無障礙可以處理的對象,通過類?AccessibilityNodeInfo?表示,通過無障礙服務(wù),可以通過它的performAction方法來觸發(fā)一些action2022-06-06

