OkHttp、Gson、Retrofit的简单使用

1.okHttp

1.导包

implementation("com.squareup.okhttp3:okhttp:4.9.0")

2.使用

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if(event?.action == MotionEvent.ACTION_DOWN){
            getRecipesByOkHttp()
        }
        return true
    }
    private fun getRecipesByOkHttp(){
        val okHttpClient = OkHttpClient()
        val request = Request.Builder()
            .url("http://v.juhe.cn/toutiao/index?type=top&key=4494d20d3e853ec01a1dafc8b901e716")
            .build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful){
                    val body = response.body?.string()
                    Log.v("cu","$body")
                }
            }

        })
    }
点击屏幕后成功获取到url的数据

2.Gson

1.导包

implementation 'com.google.code.gson:gson:2.8.6'

2.使用Json To Kotlin插件根据url创建模型

image.png

3.Gson().fromJson()

okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful){
                    val body = response.body?.string()
                    val news = Gson().fromJson(body,NewModel::class.java)
                    Log.v("cu","$news")
                }
            }
}
点击屏幕后成功获取到解析后的url数据

3.Retrofit

1.导包

//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//Coroutine
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"

2. 创建接⼝

interface NewsAPI {
 @GET("index?type=guonei&key=4494d20d3e853ec01a1dafc8b901e716")
 suspend fun getData():NewsModel
}

3.使用

val retrofit = Retrofit.Builder()
 .baseUrl("http://v.juhe.cn/toutiao/")
 .addConverterFactory(GsonConverterFactory.create())
 .build()
val api = retrofit.create(NewsAPI::class.java)
lifecycleScope.launch {
 val model = api.getData()
 model.result.data.forEach {
 Log.v("cu",it.title)
 }
}

你可能感兴趣的:(OkHttp、Gson、Retrofit的简单使用)