我需要在服务器循环中对服务器进行http查询。 我决定使用okHTTP3,因为不需要手动创建线程,并且使用cookie(使用PersistentCookieJar)很容易操作。
这是我的代码:
App.kt
class App : Application() {
companion object {
lateinit var cookieJar: ClearableCookieJar
lateinit var okHttpClient: OkHttpClient
}
override fun onCreate() {
super.onCreate()
cookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(applicationContext))
okHttpClient = OkHttpClient.Builder()
.cookieJar(cookieJar) // for session cookies
.build()
}
}
MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getQuery("https://example.com/path")
}
fun getQuery(url: String) {
Log.e("log", "getQuery start")
val request = Request.Builder()
.url(url)
.build()
App.okHttpClient.newCall(request)?.enqueue(object : okhttp3.Callback {
override fun onFailure(call: okhttp3.Call?, e: IOException?) {
Log.e("log", "onFailure " + e?.message)
}
override fun onResponse(call: okhttp3.Call?, response: okhttp3.Response?) {
val resp = response?.body()?.string()
val code = response?.code()
Log.e("log", "onResponse " + code.toString() + " " + resp )
try {
// here getting info from resp
} catch (e: Exception) {
Log.e("log", "catch " + e?.message)
} finally {
getQuery("https://example.com/path") // call in cycle
}
}
})
}
当我从okHttpClient自身调用getQuery时,什么也不做,logcat不显示onResponse,也不显示onFailure。我认为这是因为从okHttpClient创建的另一个线程进行调用。
我做错了什么?