close

在kotlin投過API GET取得資料


Strp 1:

執行API Get的 fun

private fun sendGet(url:String) {
    val connection = URL(url).openConnection() as HttpURLConnection
    try {
        val data = connection.inputStream.bufferedReader().readText()
        Log.d(TAG, data)
    } finally {
        connection.disconnect()
    }
}

將你想要取得資料的url傳入

data就會得到從API取得的資料

 

如果直接在主線程執行sebdGet這個fun的話,會出現error(android.os.NetworkOnMainThreadException),所以要執行Step2

 Step 2:

要將sendGet放到doAsync裡面,因為要確保在執行HttpURLConnection的時候不會影響到原本的主線程

doAsync {
    sendGet(url)
    // Call all operation  related to network or other ui blocking operations here.
    uiThread {
        // perform all ui related operation here
    }
}

 

要使用doAsync 這個fun要先引用Anko

在Gradle裡面加入

compile "org.jetbrains.anko:anko:0.10.4"
arrow
arrow
    文章標籤
    andorid kotlin API
    全站熱搜

    小小工程師 發表在 痞客邦 留言(2) 人氣()