我有一个web服务,在post请求中获取用户名和密码,如果http statuscode为200,则返回令牌(JWT)和代码。如果statuscode为403,则代码包含详细信息,令牌为null。在iOS上它正在运行,但现在我试图在Kotlin和Retrofit中实现它。
到目前为止我创造了什么:
2 DTO:
class LoginDto(var username: String, var password: String)
class LoginResultDto(var accessToken: String, var code: Int)
(JWT处理将是下一步)
客户服务:
interface ClientService {
@POST("authenticate")
fun login(@Body body: LoginDto): Single<LoginResultDto>
companion object {
fun create(): ClientService {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://test-backend.mydomain.com/api/")
.build()
return retrofit.create(ClientService::class.java)
}
}
}
以及调用服务的代码:
private fun login(email: String, password:String){
clientService.login(LoginDto(email,password))
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
onSuccess: LoginResultDto? ->
onSuccess?.let {
Toast.makeText(this, "token: " +it.accessToken + " code: "+it.code+ "success", Toast.LENGTH_SHORT).show()
}
},
{
onError: Throwable ->
println(onError)
Toast.makeText(this, onError.localizedMessage, Toast.LENGTH_LONG).show()
}
)
}
请求本身正在运行。它返回带有正确登录数据的200和带有错误的403。但是LoginResultDto是空的。
如何在LoginResultDto中填充结果?
答案 0 :(得分:-1)
试试这样:
您的客户服务:
interface ClientService {
@POST("authenticate")
fun login(@Body body: LoginDto): Observable<LoginResultDto>
companion object {
fun create(): ClientService {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://test-backend.mydomain.com/api/")
.build()
return retrofit.create(ClientService::class.java)
}
}}
您的来电:
private fun login(email: String, password:String){
clientService.login(LoginDto(email,password))
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result ->
if (result.isSuccessful) {
Toast.makeText(this, "token: " +result.body().accessToken + " code: "+result.body().code+ "success", Toast.LENGTH_SHORT).show()}
},
{
error ->{
println(error)
Toast.makeText(this, error.localizedMessage, Toast.LENGTH_LONG).show()
}
}
)}
依赖关系:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
}