我试图在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())
。我希望有人能知道是什么问题,因为我被困在这里很长一段时间,无法弄清楚。
提前感谢并致以亲切的问候
1条答案
按热度按时间vfh0ocws1#
你只能在
ResponseBody
上调用string()
一次,因为okhttp
从流中读取数据并且不持有引用,它抛出close,因为它已经在阅读后关闭了流!您需要调用string()
并将值存储在变量中,然后多次使用它。