Skip to content

Instantly share code, notes, and snippets.

@ruyut
Last active September 15, 2020 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruyut/354257d698da9989ff6595bce1aa6d9e to your computer and use it in GitHub Desktop.
Save ruyut/354257d698da9989ff6595bce1aa6d9e to your computer and use it in GitHub Desktop.
Get network information by OkHttp
package app.ruyut.test.okhttp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
class MainActivity : AppCompatActivity() {
private val TAG: String = MainActivity::class.java.simpleName
private val url: String = "https://data.ntpc.gov.tw/api/datasets/28AB4122-60E1-4065-98E5-ABCCB69AACA6/json/preview"
//讀取的url,以政府資料開放平台中的新北市垃圾車為例
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var client = OkHttpClient.Builder().build()
var request = Request.Builder()
.url(url)
.build()
CoroutineScope(Dispatchers.IO).launch {
var response = client.newCall(request).execute()
response.body?.run{
Log.d(TAG, "onCreate: ${string()}")
}
}
}
}
//Android8以上預設不能使用http開頭的網址,建議使用https
//需要在AndroidManifest.xml中加入網路權限聲明
//<uses-permission android:name="android.permission.INTERNET"/>
//需要在build.gradle(Module:app)中加入OkHttp函式庫
//implementation "com.squareup.okhttp3:okhttp:4.9.0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment