您好,登錄后才能下訂單哦!
Retrofit框架怎么在Android中使用?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
Android是一種基于Linux內(nèi)核的自由及開放源代碼的操作系統(tǒng),主要使用于移動(dòng)設(shè)備,如智能手機(jī)和平板電腦,由美國(guó)Google公司和開放手機(jī)聯(lián)盟領(lǐng)導(dǎo)及開發(fā)。
Retrofit是Square開源的一款基于OkHttp(也是他家的)封裝的網(wǎng)絡(luò)請(qǐng)求框架,主要的網(wǎng)絡(luò)請(qǐng)求還是OkHttp來(lái)完成,Retrofit只是對(duì)OkHttp進(jìn)行了封裝,可以讓我們更加簡(jiǎn)單方便的使用,目前大部分公司都在使用這款框架,Retrofit的原理也是面試必問的問題之一了,所以我們不僅要會(huì)使用,也要對(duì)其實(shí)現(xiàn)原理有一個(gè)大概的了解。
本片文章從使用角度來(lái)說(shuō),不對(duì)的地方希望大家在評(píng)論區(qū)交流,我會(huì)及時(shí)改進(jìn),共同進(jìn)步,文章中的demo可以從github下載。
Retrofit的大部分配置是通過注解來(lái)實(shí)現(xiàn)的,配置簡(jiǎn)單,使用方便;支持多種返回類型包括RxJava和協(xié)程,可以配置不同的解析器來(lái)進(jìn)行數(shù)據(jù)解析,如Json,xml等
以下代碼全部為Kotlin語(yǔ)言編寫,畢竟現(xiàn)在Kotlin也是大勢(shì)所趨了。
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'
<uses-permission android:name="android.permission.INTERNET"/>
首先定義一個(gè)RetrofitHelper輔助類,編寫Retrofit單例,Retrofit內(nèi)部已經(jīng)維護(hù)了線程池做網(wǎng)絡(luò)請(qǐng)求,不需要?jiǎng)?chuàng)建多個(gè)
注:BASE_URL必須為 "/" 結(jié)尾
object RetrofitHelper { //baseUrl根據(jù)自己項(xiàng)目修改 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中進(jìn)行初始化
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ò)請(qǐng)求 解決的辦法有2種 1.把所有的http請(qǐng)求全部改為https請(qǐng)求 2.在res的xml目錄(),然后創(chuàng)建一個(gè)名為:network_security_config.xml文件
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
首先我們先用一個(gè)最簡(jiǎn)單的GET請(qǐng)求來(lái)試一下,這個(gè)接口是請(qǐng)求天氣情況的,免費(fèi)的
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請(qǐng)求,GET注解的value為請(qǐng)求地址,完整的請(qǐng)求地址為baseUrl+value,如value為完整地址,則會(huì)使用value為請(qǐng)求地址,一般通用情況下baseUrl = "www.weather.com.cn/", 然后GET("data/sk/{cityCode}.html") @Path是網(wǎng)址中的參數(shù),用來(lái)替換。
5.1RxJava方法實(shí)現(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中進(jìn)行就好,首先通過Retrofit單例調(diào)用Service的對(duì)象的getWeather方法,指定上下游事件的線程,創(chuàng)建觀察者對(duì)象進(jìn)行監(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對(duì)象
2.注冊(cè)LiveData的回調(diào)
3.獲取天氣情況
如下圖所示
看完上述內(nèi)容,你們掌握 Retrofit框架怎么在Android中使用的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。