<Day28>Network-OkHttp

在android 使用 Network 需要宣告权限

  • AndroidManifest.xml 中宣告
<uses-permission 
  android:name="android.permission.INTERNET" />
  <uses-permission  
android:name="android.permission.ACCESS_NETWORK_STATE" />

使用OkHttp与Retrofit第三方套件做网路连线为例:

  • OkHttp: HTTP 连线的第三方套件的操作。
    Retrofit:通常与 OkHttp 并用,将API 定义与将资料转成物件来操作,其规范的REST API 框架让程序好写易维护。

  • import libary

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.14.9"
  }

*使用OkHttp 建立 UserApi api *

class ApiClient {

    private val okHttp: Call.Factory
    private val retrofit: Retrofit
    private val testApi: TestApi


    constructor(baseUrl: String = "api path") {
        this.okHttp = OkHttpClient.Builder()
            .addInterceptor(HttpLoggingInterceptor().apply { setLevel(HttpLoggingInterceptor.Level.NONE); })
            .build()
        this.retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(this.okHttp)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        this.testApi = retrofit.create(TestApi::class.java)
    }
    
    suspend fun getTest(Id: Int): Test {
        try {
            val response = userApi.getUser(userId)
            return if (response.isSuccessful) {
                response.body()!!.data
            } else {
                throw Exception("should success")
            }
        } catch (e: Exception) {
            throw e
        }
    }

 }

UserApi getTest func

interface TestApi {

    companion object {
        const val PATH_ID = "id"
    }

    @GET("users/{$PATH_ID}")
    suspend fun getTest(@Path(PATH_ID) Id: Int): Response<ParsingData<Test>>

}


data class ParsingData<T>(
      @SerializedName("data") val id: data
)

使用Gson UserApi GSON 转为物件

class Test(
    @SerializedName("id") val id: Int,
    @SerializedName("name") var name: String
)

提醒一下,要注意 OkHttp与 Retrofit 版本支援 , Android 4.x(含以下)的版本,OkHttp 只能用 3.12.x,Retrofit 只能用 2.6.4。

reference:https://square.github.io/retrofit/
reference:https://developer.android.com/training/basics/network-ops/connecting
reference:https://www.notion.so/Network-10-7-Cateyes-0c18aaf956ba4c7487e6116f29730263
reference:https://ithelp.ithome.com.tw/articles/10188660


<<:  从零开始-30日练习开发iOS APP-UserDefault Day-28

>>:  [LeetCode30] Day26 - 1106. Parsing A Boolean Expression

端点防护软件 - 政府组态基准 GCB

灌了政府两字,果然威能,请小心服用... 适用人员: 技术人员。 适用法规: 资通安全责任等级分级办...

Google无法移除侵权网址127.0.0.1

故事从 127.0.0.1这个网址用於localhost,表示为本机端,也会被用来测试网路状况......

快取机制 心得纪录

这几天听到一个新名词,eTag,我想说这究竟是什麽东西,要上高速公路了吗?、还是什麽特别的tag呢?...

[Day 29] tinyML应用实例分享

话说受到火鸡姐的鼓舞(其实是逃命),我来到了中国厨艺学院(其实是少林寺的伙房)拜师学艺,没想到得罪了...

30天打造品牌特色电商网站 Day.19 文字的排版

字距、行距、与其他物件的距离,调整适当能让使用者有舒服的体验,而良好的排版能引导使用者优先接收整个画...