OkHttpClient() POST 的问题不工作 KOTLIN

Troubles with OkHttpClient() POST not working KOTLIN

我正在尝试进行同步调用,该调用需要在继续将用户存储在云中之前完成。我认为问题出在 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。也许它以某种方式形成了错误的调用。如果可以请帮忙。

尝试 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()
    }
}