0
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()
    }
}

Using android studio and kotlin. Trying to call an API but all I get is NULL instead of the string it should be getting.

Additionally how do I add basic authentication to this (username/password) if the API required it?

Also what does "@Throws" do?

ReinForce
  • 101
  • 2
  • 6
  • 11

2 Answers2

1

To start off with, I'd suggest looking into retrofit as I personally find it easier to work with (though may be overkill if you're only making one or two REST calls)

I'd also probably do

client.newCall(request).enqueue(object: Callback {
    override fun onResult(call: Call, response: Response) {
        if (response.isSuccessful()) {
            return@run response.body.toString()
        }
    }
)}

to be asynchronous.

Authentication is a pain to add in OkHttp imo and is best answered from here, and much easier in Retrofit.

Finally, Throws marks the function as having the potential to throw an Exception when called from Java code (as Kotlin and Java can co-exist)

Joshua Feltimo
  • 323
  • 1
  • 3
  • 12
  • Thanks. This is a learning exercise which I plan to scale up so will move to retrofit. Where can I find kotlin exmaples for these libraries? Everything seems to be Java. I have to use a lot of trail and error to convert the code even after using the auto code converter. – ReinForce Mar 01 '19 at 09:55
  • @ReinForce [this looks fairly useful](https://medium.com/@elye.project/kotlin-and-retrofit-2-tutorial-with-working-codes-333a4422a890) – Joshua Feltimo Mar 02 '19 at 21:20
1

Longer explanation through code

@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()
}
  • `Log.d("Exception", e.toString())` where does this log get stored? would it be on the android device root of internal storage at a text file? So if I add a new thread, then I need to change back to the UI thread, how do I know what the current active thread is? – ReinForce Mar 01 '19 at 10:37
  • Log just used for checking any necessary debugging program and can be view in log section in your IDE. For example using Log you can know the error exception without view the error in the application – Septian Triadi Mar 01 '19 at 11:58