欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android網(wǎng)絡(luò)訪(fǎng)問(wèn)之Retrofit使用教程

 更新時(shí)間:2022年12月13日 14:37:27   作者:懶到死的程序員  
Retrofit?是一個(gè)?RESTful?的?HTTP?網(wǎng)絡(luò)請(qǐng)求框架的封裝,網(wǎng)絡(luò)請(qǐng)求的工作本質(zhì)上是?OkHttp?完成,而?Retrofit?僅負(fù)責(zé)?網(wǎng)絡(luò)請(qǐng)求接口的封裝

一、概念

HttpClientAndroid 6中移除(API數(shù)量多擴(kuò)展困難)。
HttpURLConnection目前官方集成的。
OKHttpSquare公司出品,底層通訊的實(shí)現(xiàn)。
RetrofitSquare公司出品,上層接口的封裝,更方便使用面向?qū)ο笏季S進(jìn)行網(wǎng)絡(luò)操作。

二、使用

Android 9開(kāi)始默認(rèn)只允許使用 HTTPS 類(lèi)型的網(wǎng)絡(luò)請(qǐng)求,HTTP明文傳輸因?yàn)橛邪踩[患不再支持。堅(jiān)持使用的話(huà)需要配置:右鍵res目錄→New→Directory→創(chuàng)建一個(gè)xml目錄,右鍵xml目錄→New→File→創(chuàng)建一個(gè)network_config.xml文件,修改內(nèi)容如下:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

Manifest {
    //添加網(wǎng)絡(luò)訪(fǎng)問(wèn)權(quán)限
    <uses-permission android:name="android.permission.INTERNET" />
    //允許HTTP訪(fǎng)問(wèn)
    <application
        android:networkSecurityConfig="@xml/network_config"
    </application>
}

2.1HttpURLConnection

thread {
    var connection: HttpURLConnection? = null
    try {
        val response = StringBuilder()
        val url = URL("https://www.baidu.com")
        connection = url.openConnection() as HttpURLConnection
        connection.connectTimeout = 8000
        connection.readTimeout = 8000
        //GET請(qǐng)求
        val input = connection.inputStream
        val reader = BufferedReader(InputStreamReader(input))
        reader.useLines { response.append(it) }
        print(response.toString())
        //POST請(qǐng)求
        connection.requestMethod = "POST"
        val output = DataOutputStream(connection.outputStream)
        output.writeBytes("username=admin&password=123456")
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        connection?.disconnect()
    }
}

2.2OKHttp

傳送門(mén)

2.3Retrofit

查看最新版本

implementation 'com.squareup.retrofit2:retrofit:2.9.0'    //會(huì)連帶下載 OkHttp和Okio
implementation 'com.squareup.retrofit2:converter-gson:2.k6.1'    //會(huì)連帶下載 GSON

2.3.1 定義實(shí)體類(lèi)

根據(jù) JSON 內(nèi)容,編寫(xiě)對(duì)應(yīng)的實(shí)體類(lèi)。

data class Person(var name: String, var age: Int)

2.3.2 定義API接口

根據(jù) API 接口,編寫(xiě)對(duì)應(yīng)的訪(fǎng)問(wèn)文件。命名通常以功能名稱(chēng)開(kāi)頭+Service結(jié)尾。

@GET從服務(wù)器獲取數(shù)據(jù)
@POST向服務(wù)器提交數(shù)據(jù)
@PUT @PATCH修改服務(wù)器上的數(shù)據(jù)
@DELETE刪除服務(wù)器上的數(shù)據(jù)
interface PersonService {
    //接口1:https://www.baidu.com/person.json
    @GET("person.json")    //表示發(fā)起的是GET請(qǐng)求,傳入請(qǐng)求的地址(相對(duì)路徑,重復(fù)根路徑在后面配置)
    fun getPerson(): Call<list<Person>>    //返回值必須聲明成Retrofit內(nèi)置的Call類(lèi)型,通過(guò)泛型指定服務(wù)器返回的具體數(shù)據(jù)類(lèi)型
    //接口2:https://www.baidu.com/<page>/person.json
    @GET("{page}/get_data.json")    //使用 {page} 占位
    fun getData(@Path("page") page: Int): Call<Data>    //使用 @Path("page")注解來(lái)聲明對(duì)應(yīng)參數(shù)
    //接口3:https://www.baidu.com/person.json?u=<user>&t=<token>
    @GET("person.json")
    fun getData(@Query("u") user: String, @Query("t") token: String): Call<Data>
    //接口4:https://api.caiyunapp.com/v2/place?query=北京&token={token}&lang=zh_CN
    @GET("v2/place?token=${GlobalApplication.TOKEN}&lang=zh_CN")    //不變的參數(shù)固定寫(xiě)在GET里
    fun searchPlaces(@Query("query") query: String): Call<PlaceResponse>
    //接口5:https://www.baidu.com/data/<id>
    @DELETE("data/{id}")
    fun deleteData(@Path("id") id: String): Call<ResponseBody>    //該泛型表示能接受任意類(lèi)型切不會(huì)進(jìn)行解析
    //接口6:https://www.baidu.com/data/create{"id": 1, "content": "The description for this data."}
    @POST("data/create")
    fun createData(@Body data: Data): Call<ResponseBody>    //將Data對(duì)象中的數(shù)據(jù)轉(zhuǎn)換成JSON格式的文本,并放到HTTP請(qǐng)求的body部分
    //接口7:http://example.com/get_data.json
    //      User-Agent: okhttp    //header參數(shù)就是鍵值對(duì)
    //      Cache-Control: max-age=0
    //靜態(tài)聲明
    @Headers("User-Agent: okhttp", "Cache-Control: max-age=0")
    @GET("get_data.json")
    fun getData(): Call<Data>
    //動(dòng)態(tài)聲明
    @GET("get_data.json")
    fun getData(@Header("User-Agent") userAgent: String, @Header("Cache-Control") cacheControl: String): Call<Data>
}

2.3.3 構(gòu)建Retrofit對(duì)象

val retrofit = Retrofit.Builder()
    .baseUrl("https://www.baidu.com/")    //配置重復(fù)的根路徑
    .addConverterFactory(GsonConverterFactory.create())    //指定解析數(shù)據(jù)使用的轉(zhuǎn)換庫(kù)(這里是Gson)
    .build()

2.3.4 創(chuàng)建API接口實(shí)例并調(diào)用訪(fǎng)問(wèn)函數(shù)

//創(chuàng)建動(dòng)態(tài)代理對(duì)象
val personService = retrofit.create(PersonService::class.java)
//調(diào)用訪(fǎng)問(wèn)函數(shù)
personService.getPerson().enqueue(object : Call<List<person>> {    //根據(jù)注解中配置的地址進(jìn)行網(wǎng)絡(luò)請(qǐng)求
    override fun onResponse(call: Call<List<person>>, response: Response<List<person>>) {
        val list = response.body()    //得到解析后的對(duì)象
    }
    override fun onFailure(call: Call<List<person>>, t: Trouble) {
        t.printStackTrace()
    }
})

2.3.5 優(yōu)化

object GlobalRetrofit {
    private const val BASE_URL = "www.baidu.com/"
    val retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    //fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)
    inline fun <reified T> create(): T = create(T::class.java)
}
//使用
val personService = GlobalRetrofit.create<PersonService>()

到此這篇關(guān)于Android網(wǎng)絡(luò)訪(fǎng)問(wèn)之Retrofit使用教程的文章就介紹到這了,更多相關(guān)Android Retrofit內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android編程實(shí)現(xiàn)將ButtonBar放在屏幕底部的方法

    Android編程實(shí)現(xiàn)將ButtonBar放在屏幕底部的方法

    這篇文章主要介紹了Android編程實(shí)現(xiàn)將ButtonBar放在屏幕底部的方法,涉及Android界面設(shè)計(jì)與文本操作相關(guān)技巧,需要的朋友可以參考下
    2017-03-03
  • Android實(shí)現(xiàn)環(huán)形進(jìn)度條

    Android實(shí)現(xiàn)環(huán)形進(jìn)度條

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)環(huán)形進(jìn)度條,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Android編程之TabWidget選項(xiàng)卡用法實(shí)例分析

    Android編程之TabWidget選項(xiàng)卡用法實(shí)例分析

    這篇文章主要介紹了Android編程之TabWidget選項(xiàng)卡用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了TabWidget選項(xiàng)卡的具體實(shí)現(xiàn)技巧與使用注意事項(xiàng),需要的朋友可以參考下
    2015-12-12
  • Android生成隨機(jī)數(shù)的方法實(shí)例

    Android生成隨機(jī)數(shù)的方法實(shí)例

    這篇文章主要為大家詳細(xì)介紹了Android生成隨機(jī)數(shù)的方法實(shí)例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-03-03
  • Android自定義PhotoView使用教程

    Android自定義PhotoView使用教程

    自定義 PhotoView 繼承(extends)自 View。并在最中間顯示后面操作的圖片。繪制圖片可以重寫(xiě) onDraw()方法,并在里面通過(guò)Canvas.drawBitmap()來(lái)要繪制圖片
    2023-04-04
  • Android ContentProvider獲取手機(jī)聯(lián)系人實(shí)例

    Android ContentProvider獲取手機(jī)聯(lián)系人實(shí)例

    這篇文章主要介紹了Android ContentProvider獲取手機(jī)聯(lián)系人實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-02-02
  • 非常好看的android音量旋鈕

    非常好看的android音量旋鈕

    這篇文章主要為大家詳細(xì)介紹了android好看的音量旋鈕,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • 快速關(guān)閉android studio的自動(dòng)保存功能教程

    快速關(guān)閉android studio的自動(dòng)保存功能教程

    這篇文章主要介紹了快速關(guān)閉android studio的自動(dòng)保存功能教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • 詳解Android中獲取軟鍵盤(pán)狀態(tài)和軟鍵盤(pán)高度

    詳解Android中獲取軟鍵盤(pán)狀態(tài)和軟鍵盤(pán)高度

    這篇文章主要介紹了詳解Android中獲取軟鍵盤(pán)狀態(tài)和軟鍵盤(pán)高度的相關(guān)資料,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下
    2017-10-10
  • Android中傳值Intent與Bundle的區(qū)別小結(jié)

    Android中傳值Intent與Bundle的區(qū)別小結(jié)

    這篇文章主要給大家總結(jié)介紹了關(guān)于Android中傳值Intent與Bundle的區(qū)別,文中通過(guò)示例代碼以及圖文介紹的非常詳細(xì),對(duì)各位Android開(kāi)發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03

最新評(píng)論