Android之Kotlin:Kotlin 使用Retrofit2.0

image.png

首先导入gradle Retrofit2.0

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    //okhttp提供的请求日志拦截器
    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

API类:接口地址常量类

/**
 * 接口常量类
 */
object Api{
    const val BASE_URL:String = "http://mobile.bwstudent.com/"
    const val LOGIN_URL:String = "small/user/v1/login"
}

接口声明类:UserApiService

/**
 * 接口声明类
 */
interface UserApiService{

    @POST
    @FormUrlEncoded
    fun login(@Url string: String,@Field("phone") mobile:String,@Field("pwd")pwd: String):Call

}

实体类

/**
 * 实体类:通过jsontokotlin插件生成
 */
data class UserBean(
    val message: String,
    val result: Result,
    val status: String
)

data class Result(
    val headPic: String,
    val nickName: String,
    val phone: String,
    val sessionId: String,
    val sex: Int,
    val userId: Int
)

直接在MainActivity 请求数据

class MainActivity : AppCompatActivity(), View.OnClickListener {

   

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()

    }

    private fun initView() {

        login.setOnClickListener(this)

    }

    /**
     * 登录测试
     */
    fun login() {

        Toast.makeText(this, "login", Toast.LENGTH_SHORT).show()

        var mobile: String = mobile.text.toString()
        mobile = "18612991023"
        var pwd = "111111"
        //日志拦截器
        var httpLoggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
        //Okhttp对象
        var okHttpClient = OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .build()

        //创建Retrofit对象
        var retrofit = Retrofit.Builder().baseUrl(Api.BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create()).build()

        //创建请求接口类
        var userApiService = retrofit.create(UserApiService::class.java)
        userApiService.login(Api.LOGIN_URL, mobile, pwd).enqueue(object : retrofit2.Callback {
            override fun onFailure(call: Call, t: Throwable) {

            }

            override fun onResponse(call: Call, response: Response) {

                var userBean = response.body()
                Toast.makeText(this@MainActivity, "" + userBean?.result?.phone, Toast.LENGTH_SHORT).show()

            }

        })
    }

    /**
     * 点击事件
     */
    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.login -> login()
            R.id.reg -> reg()
        }
    }

    /**
     * 注册测试
     */
    private fun reg() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

你可能感兴趣的:(Android之Kotlin:Kotlin 使用Retrofit2.0)