如何使用Retrofit2请求获得令牌授权?

时间:2019-02-22 15:23:27

标签: java android kotlin retrofit2

我正在尝试使用Retrofit 2向服务器发出POST请求,并获取授权令牌以进一步处理服务器。 响应码= 400 ... login和passwod存储在Login类中。 这是服务器身份验证方法:

enter image description here

我的MainActivity:

class MainActivity : AppCompatActivity() {

    val bulder = Retrofit.Builder()
        .baseUrl("https://tv-server.trinity-tv.net/server/TvServerService/")
        .addConverterFactory(GsonConverterFactory.create())

    val retrofit: Retrofit = bulder.build()
    val userClient: UserClient = retrofit.create(UserClient::class.java)


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

        login_btn.setOnClickListener { login() }
    }

    private fun login() {
        val login = Login("1", "2")
        val call: Call<User> = userClient.getLogin(login)

        call.enqueue(object : Callback<User> {

            override fun onResponse(call: Call<User>, response: Response<User>) {
                response.code()
                if (response.isSuccessful){
                    Toast.makeText(this@MainActivity, response.body()?.token, Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(this@MainActivity, "ERROR", Toast.LENGTH_LONG).show()
                }
            }

            override fun onFailure(call: Call<User>, t: Throwable) {

            }
        })
    }
}

我的界面:

interface UserClient {

    @POST("Auth")
    fun getLogin(@Body login: Login) : Call<User>
}

0 个答案:

没有答案