为什么我在Kotlin中尝试向.json文件写入OkHttp响应时会出现“关闭”异常?

2w3kk1z5  于 2023-05-23  发布在  Kotlin
关注(0)|答案(1)|浏览(142)

我试图在Kotlin中创建一个货币转换应用程序,并且在更新我的值时遇到了问题。连接工作正常,但我无法将其写入.json文件。下面是我的代码:

val request = Request.Builder().url(url).header("apikey", key).build()

        val client = OkHttpClient()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {}
            override fun onResponse(call: Call, response: Response) {
                println(response.body()?.string())
                val date = LocalDate.now()
                val osw = OutputStreamWriter(openFileOutput("$date.json", MODE_PRIVATE))
                osw.write(response.body()?.string())
                println("finished")
            }
        })
    }
Here is the Error: 
E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: com.example.appdevelopment_assignment_7, PID: 6787
    java.lang.IllegalStateException: closed
        at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:398)
        at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:392)
        at okhttp3.internal.Util.bomAwareCharset(Util.java:431)
        at okhttp3.ResponseBody.string(ResponseBody.java:174)
        at com.example.appdevelopment_assignment_7.ComplexCurrencyConversionActivity$update$1.onResponse(ComplexCurrencyConversionActivity.kt:36)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:141)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
        at java.lang.Thread.run(Thread.java:1012)

有问题的行是osw.write(response.body()?.string())。我希望有人能知道是什么问题,因为我被困在这里很长一段时间,无法弄清楚。
提前感谢并致以亲切的问候

vfh0ocws

vfh0ocws1#

你只能在ResponseBody上调用string()一次,因为okhttp从流中读取数据并且不持有引用,它抛出close,因为它已经在阅读后关闭了流!您需要调用string()并将值存储在变量中,然后多次使用它。

val request = Request.Builder().url(url).header("apikey", key).build()

val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {}
    override fun onResponse(call: Call, response: Response) {
        val responseBody = response.body()?.string() // stream closed after invoking string()
        println(responseBody)
        val date = LocalDate.now()
        val osw = OutputStreamWriter(openFileOutput("$date.json", MODE_PRIVATE))
        osw.write(responseBody)
        println("finished")
    }
})
}

相关问题