安卓应用技术开发

Android之Kotlin:Kotlin 使用Retrofit

2019-03-30  本文已影响0人  STE北京老徐
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<UserBean>

}

实体类

/**
 * 实体类:通过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<UserBean> {
            override fun onFailure(call: Call<UserBean>, t: Throwable) {

            }

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

                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.
    }
}
上一篇下一篇

猜你喜欢

热点阅读