【发布时间】:2019-07-22 16:35:29
【问题描述】:
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.lang.Exception
...
private val client = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tvDisplay: TextView = findViewById(R.id.displayTV) as TextView
tvDisplay.setOnClickListener {
tvDisplay.text = run("https://jsonplaceholder.typicode.com/todos/1")
}
}
@Throws(IOException::class)
fun run(url: String): String {
val request = Request.Builder()
.url(url)
.build()
try {
client.newCall(request).execute().use { response -> return response.body().toString() }
}
catch (e: Exception) {
return e.message.toString()
}
}
使用 android studio 和 kotlin。尝试调用 API 但我得到的只是 NULL 而不是它应该得到的字符串。
此外,如果 API 需要,我如何向此(用户名/密码)添加基本身份验证?
“@Throws”还有什么作用?
【问题讨论】:
标签: android rest kotlin textview okhttp3