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需要,如何为此(用户名/密码)添加基本身份验证?
“@ Thows”也有什么作用?
首先,我建议调查retrofit,因为我个人觉得它更容易使用(如果你只做一个或两个REST调用可能会有点过分)
我也可能这样做
client.newCall(request).enqueue(object: Callback {
override fun onResult(call: Call, response: Response) {
if (response.isSuccessful()) {
return@run response.body.toString()
}
}
)}
异步。
身份验证在OkHttp imo中添加很难,最好从here回答,在Retrofit中更容易。
最后,Throws
将该函数标记为有可能在从Java代码调用时抛出Exception
(因为Kotlin和Java可以共存)
通过代码更长的解释
@Throws(IOException::class) // If IOException occur it will throw error to its parent the one that call to this function so you do not need try catch in this function
fun run(url : String) : Response{
val request = Request.Builder()
.url(url)
.get()
.build()
val client = OkHttpClient()
return client.newCall(request).execute()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tvDisplay: TextView = findViewById(R.id.displayTV) as TextView
val thread = object : Thread() { //Always use another thread from UIthread so UI will not lock while waiting get response from API
override fun run() {
try{
val _response = run("https://jsonplaceholder.typicode.com/todos/1").body()!!.string()
runOnUiThread { //Change to UI thread again if you need change somthing in UI
tvDisplay.setText(_response)
}
}
catch(e: Excpetion){
Log.d("Exception", e.toString()) //if anything error it goes here
}
}
}
thread.start()
}