一贫悄、 前期準(zhǔn)備工作
在gradle文件里的dependencies中加入
implementation'com.squareup.okhttp3:okhttp:4.9.1'
然后就記得開(kāi)網(wǎng)絡(luò)權(quán)限
在xml文件中加入權(quán)限請(qǐng)求
<uses-permission android:name="android.permission.INTERNET" />
1.1 http請(qǐng)求的設(shè)置
這樣還不夠泊碑,因?yàn)閍ndroid9.0后不支持http網(wǎng)絡(luò)請(qǐng)求枕赵,會(huì)報(bào)錯(cuò),只需要https請(qǐng)求可忽略這一步蝇完。
需要在res文件下建立一個(gè)xml文件,在這個(gè)文件夾下建立一個(gè)network_security_config.xml文件,如圖所示
文件里可以自定義哪些網(wǎng)址能夠請(qǐng)求讹蘑,簡(jiǎn)單的寫(xiě)法是
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />?
</network-security-config>
二怀樟、 簡(jiǎn)單的請(qǐng)求函數(shù)
這里封裝一個(gè)簡(jiǎn)單的函數(shù)功偿,展示使用流程
protected open fun post(url:String, content:String) {
Log.d("---tag---url:", url)
var url = url
var mediaType ="text/x-markdown; charset=utf-8".toMediaTypeOrNull()
var request =Request.Builder()
.url(url)
.post(RequestBody.create(mediaType,""))
.build()
val okHttpClient = OkHttpClient()
okHttpClient.newCall(request).enqueue(object :Callback {
override fun onFailure(call:Call, e:IOException) {
Log.d("---tag---請(qǐng)求失敗","onFailure: " + e.message)
}
@Throws(IOException::class)
override fun onResponse(call:Call, response:Response) {
Log.d("----tag---消息體:", response.protocol.toString() +" " + response.code +" " + response.message+" "+ (response.body?.string() ?:""))
val headers = response.headers
? ? ? ? ? ? Looper.prepare()
Looper.loop()
}
})
}
三、測(cè)試api
這里提供一個(gè)測(cè)試用的api接口
http://cre.dp.sina.cn/api/v3/get?cateid=3Nh&cre=tianyi&mod=wfashion&merge=3&statics=1&length=20&tm=1489716199&ad=%7B%22rotate_count%22:5932,%22page_url%22:%22http://fashion.sina.cn/%22,%22channel%22:%22131036%22,%22platform%22:%22wap%22,%22timestamp%22:1515927821661,%22net%22:null%7D&action=1&up=2&down=0&length=12&_=1515927824733&callback=Zepto15159278216351
一套簡(jiǎn)單的請(qǐng)求流程就完成了
如果描述有誤往堡,懇請(qǐng)批評(píng)指正脖含,萬(wàn)分感謝!