Android

安卓使用Retrofit发起http请求

2020-11-07  本文已影响0人  梁典典

1.首先导个包

    implementation 'com.squareup.retrofit2:retrofit:2.6.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.1'

2. 配置一下权限

<uses-permission android:name="android.permission.INTERNET" />
android:networkSecurityConfig="@xml/network_config"

-----------------新建res/xml/network_config.xml

<?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>

3. 创建一个服务接口


import retrofit2.Call
import retrofit2.http.GET

interface DtkService {

    @GET("api/v1/dtk/apis/categorys")
    fun getCategorys() : Call<String>
}

4. 封装一下Retrofit,单例类


import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ServiceCreator {

    private const val BASE_URL = "http://192.168.199.118:8089/"

    private val retrofit =
        Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
            .build()

    fun <T> create(serverClass: Class<T>): T = retrofit.create(serverClass)

    inline fun <reified T> create(): T = create(T::class.java)

}

5.使用

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val btn: Button = findViewById<Button>(R.id.getAppDataBtn)
        btn.setOnClickListener {
            val dtkService = ServiceCreator.create<DtkService>()
            dtkService.getCategorys().enqueue(object : Callback<String> {
                override fun onResponse(call: Call<String>, response: Response<String>) {
                    Log.d("MAIN - CATEGORY", response.body().toString())
                }
                override fun onFailure(call: Call<String>, t: Throwable) {
                    Log.d("Main", "获取失败")
                    t.printStackTrace()
                }

            })
        }


    }
}
上一篇下一篇

猜你喜欢

热点阅读