【发布时间】:2019-09-22 11:06:33
【问题描述】:
我对 Kotlin 中的 Retrofit 和 RxJava2 有疑问。
这是我的build.gradle:
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.1' implementation 'com.squareup.retrofit2:converter-moshi:2.6.1'
implementation 'com.squareup.okhttp3:okhttp:4.2.0'
implementation 'com.squareup.moshi:moshi-kotlin:1.8.0'
// RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.11'
我有以下带有单个请求的改造界面,login。我还有一个简单的data class,叫做User。
data class User (
private val firstName: String
)
interface ApiService {
@POST("auth/login")
fun login(@Body body: String) : Observable<User>
}
当我尝试发出请求并订阅它时,没有发送任何请求。我检查了我的服务器日志,但服务器根本没有收到任何东西。应用程序日志中也没有错误。我不确定我做错了什么,因为我看过很多文章/教程,他们都说要这样做。
val client = Retrofit.Builder()
.baseUrl("https://example.com/api/")
.addCallAdapterFactory(RxJava2CallAdapaterFactory.create())
.build()
.create(ApiService::class.java)
client.login(JSONObject().put("email", ...).toString())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
谁能向我解释我实际上做错了什么?
编辑:
我已经尝试了以下代码,但仍然得到相同的结果。没有请求。
val okHttpClient = OkHttpClient.Builder().addInterceptor(
HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
).build()
val client = Retrofit.Builder()
.baseUrl("https://example.com/api/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
.create(ApiClient::class.java)
client.login(JSONObject().put("email", ...).toString())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ user -> println(user) }, { error -> println(error) })
【问题讨论】:
-
从baseurl baseUrl("example.com/api") 或@POST("auth/login") 中的任何一个位置中删除最后一个/。不能同时从两者中删除
-
它仍然没有发出 API 请求。我之前已经试过了。
-
将
onError实现添加到subscribe(..)函数并记录错误 -
你是在建议
.subscribeBy(onError = { throwable -> Log.e(throwable.toString()) }),因为这绝对不会向控制台记录任何内容。 -
首先尝试按照改造文档中的这个简单示例,并向 github 的 api 发出请求。 square.github.io/retrofit
https://api.github.com/users/{users}/repos。当您成功进行改造工作后,将 apis 更改为您自己的服务器。如果之后出现问题,那就是服务器问题。
标签: android kotlin retrofit2 rx-java2