LoginSignup
0
0

Android Studio: OkHttp の使い方

Last updated at Posted at 2023-10-15

設定

AndroidManifest.xml
(省略)
<uses-permission android:name="android.permission.INTERNET" />
(省略)
build.gradele.kts(Module app)
(省略)
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.10.0")
(省略)

プログラム

MainActivity.kt
package com.example.okhttp01

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.util.Log

import okhttp3.*
import java.io.IOException
import java.lang.Thread.currentThread

class MainActivity : AppCompatActivity() {

    val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        println("*** check *** aaa ***")
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        println("*** check *** ccc ***")

     //   var url_aa = "https://toridge.com/params.php"
     //   var url_aa="https://httpbin.org/get"
        var url_aa = "https://ekzemplaro.org/storytelling/repertoire/others.json"
        run(url_aa)
    }

    fun run(url: String) {
        println("*** run *** ddd ***")
        val request = Request.Builder()
            .url(url)
            .build()
        Log.i("toridge.okhttp3.run()", "Thread is " + currentThread().name) // Thread is main

        client.newCall(request).enqueue(object : Callback {

            override fun onFailure(call: Call, e: IOException) {}

            override fun onResponse(call: Call, response: Response) {
                println("*** onResponse *** fff ***")
                val request = Request.Builder()
                println(response.body!!.string())
                println("*** onResponse *** hhh ***")

            }
        })
    }
}

実行結果

View -> Tool Windows -> Logcat
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0