我正在嘗試進行同步呼叫,該呼叫需要在繼續將用戶存盤在云中之前完成。我相信問題出在 RequestBody 中,因為它看起來只是一個位元組陣列。下面是代碼:
val client = OkHttpClient()
val mediaType: MediaType? = "application/json".toMediaTypeOrNull()
val body: RequestBody =
RequestBody.create(mediaType, "{\"type\":\"DEFAULT\",\"name\":\"lkjlkj\"}")
val request: Request = okhttp3.Request.Builder()
.url("https://api.example.com/endpoint")
.post(body)
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.addHeader(
"Authorization",
"Bearer SK-xxxxxx-4QAXH"
)
.build()
Toast.makeText(this@RegisterActivity, "Entering Call",Toast.LENGTH_SHORT).show()
val response: Unit = client.newCall(request).execute().use {
Toast.makeText(this@RegisterActivity, "sent call, awaiting response",Toast.LENGTH_SHORT).show()
if (it.isSuccessful){
val content = JSONObject(it.body.toString())
desiredString = content.getJSONArray("desiredStringField").toString()
Toast.makeText(this@RegisterActivity, desiredString,Toast.LENGTH_SHORT).show()
}
if (!it.isSuccessful){
Toast.makeText(this@RegisterActivity, "failed",Toast.LENGTH_SHORT).show()
}
}
代碼不會崩潰,但似乎呼叫永遠不會完成,因為它永遠不會進入 it.isSuccessful 或 !it.isSuccessful。也許它以某種方式形成了錯誤的呼叫。如果可以的話請幫忙。
uj5u.com熱心網友回復:
嘗試enqueue請求并使用以下命令管理回應Callback:
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful){
Toast.makeText(this@RegisterActivity, "failed",Toast.LENGTH_SHORT).show()
return
}
try {
val content = JSONObject(response.body?.string() ?: "")
desiredString = content.getJSONArray("desiredStringField").toString()
Toast.makeText(this@RegisterActivity, desiredString,Toast.LENGTH_SHORT).show()
} catch (e: JSONException) {
// Error parsing JSON object
}
}
override fun onFailure(call: Call, e: IOException) {
Toast.makeText(this@RegisterActivity, "failed",Toast.LENGTH_SHORT).show()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/443742.html
