美文网首页Android
安卓使用Retrofit发起http请求

安卓使用Retrofit发起http请求

作者: 梁典典 | 来源:发表于2020-11-07 17:26 被阅读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()
                    }
    
                })
            }
    
    
        }
    }
    

    相关文章

      网友评论

        本文标题:安卓使用Retrofit发起http请求

        本文链接:https://www.haomeiwen.com/subject/wjhqbktx.html