Android 在Kotlin中改进解析结果
我有一个Web服务,它在post请求中使用用户名和密码,如果http statuscode为200,则返回一个令牌(JWT)和一个代码。如果statuscode为403,则代码包含详细信息,且令牌为空。在iOS上,它正在工作,但现在我正在尝试在Kotlin中实现它并进行改进 到目前为止,我所创造的: 2个DTO:Android 在Kotlin中改进解析结果,android,kotlin,retrofit2,Android,Kotlin,Retrofit2,我有一个Web服务,它在post请求中使用用户名和密码,如果http statuscode为200,则返回一个令牌(JWT)和一个代码。如果statuscode为403,则代码包含详细信息,且令牌为空。在iOS上,它正在工作,但现在我正在尝试在Kotlin中实现它并进行改进 到目前为止,我所创造的: 2个DTO: class LoginDto(var username: String, var password: String) class LoginResultDto(var accessT
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)
}
}
}
请求本身正在工作。它返回一个带有正确登录数据的200和一个带有不正确登录数据的403。但是LoginResultDto是空的
如何在LoginResultDto中填充结果?尝试如下操作:
您的客户服务:
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)
}
}}
依赖关系:
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"
}
如果我像你建议的那样更改它,很多属性都无法解决:result,body(),等等。ClientService中的响应类型Single是否仍然正确?是的,Single是正确的,但是如果你仍然面临这个问题,那么试着在“Observable”中扭曲它。你能编辑你的帖子吗?我不明白你的意思。
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"
}