[Android] 007. HTTP通信(OkHttp3)

ついでにOkHttp3の場合

OkHttp3を使用するため以下の依存関係の追加

com.squareup.okhttp3:okhttp

他の設定は省略

private val client = OkHttpClient.Builder()
    .connectTimeout(3000, TimeUnit.MILLISECONDS)
    .readTimeout(3000, TimeUnit.MILLISECONDS)
    .build()

fun sendRequest(url: String) {
    val request = Request.Builder().url(url).build()

    client.newCall(request).enqueue(object : Callback {
        override fun onResponse(call: Call, response: Response) {
            Log.d("sendRequest", response.body.string())
        }
        override fun onFailure(call: Call, e: IOException) {
            Log.e("sendRequest", e.toString())
        }
    })
}

const val BASE_URL = "http://10.0.2.2:4010"
@Composable
fun Screen(modifier: Modifier = Modifier) {
    Column(modifier) {
        Button(onClick = { sendRequest("$BASE_URL/test?id=1") }) {
            Text("GET")
        }
    }
}

Android Studio Koala 2024.1.1 Patch 1 built on July 11, 2024