こちらと同じことを行いました。
Recipes
Synchronous Get です。
サーバーは、こちらと同じ設定とします。
IntelliJ: Java 標準ライブラリーで HTTP リクエスト
環境
build.gradele.kts
(省略)
dependencies {
implementation ("com.squareup.okhttp3:okhttp:4.11.0")
testImplementation(kotlin("test"))
(省略)
}
プログラム
Main.kt
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("https://ekzemplaro.org/tmp/country_all.json")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
for ((name, value) in response.headers) {
println("$name: $value")
}
println(response.body!!.string())
}
}
fun main(){
run()
}
実行結果
/usr/lib/jvm/java-1.21.0-openjdk-amd64/bin/java -javaagent:/snap/intellij-idea-community/464/lib/idea_rt.jar=38511:/snap/intellij-idea-community/464/bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /home/uchida/IdeaProjects/get05/build/classes/kotlin/main:/home/uchida/.gradle/caches/modules-2/files-2.1/com.squareup.okhttp3/okhttp/4.10.0/cd63657ac15770ed1420647154c9f44645533bef/okhttp-4.10.0.jar:/home/uchida/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk8/1.9.0/e000bd084353d84c9e888f6fb341dc1f5b79d948/kotlin-stdlib-jdk8-1.9.0.jar:/home/uchida/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.9.0/8ee15ef0c67dc83d874f412d84378d7f0eb50b63/kotlin-stdlib-1.9.0.jar:/home/uchida/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk7/1.9.0/f320478990d05e0cfaadd74f9619fd6027adbf37/kotlin-stdlib-jdk7-1.9.0.jar:/home/uchida/.gradle/caches/modules-2/files-2.1/com.squareup.okio/okio-jvm/3.0.0/ab5a73fa2ccb4a36b0b5c69fe10b16d0255bcf8/okio-jvm-3.0.0.jar:/home/uchida/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.9.0/cd65c21cfd1eec4d44ef09f9f52b6d9f8a720636/kotlin-stdlib-common-1.9.0.jar:/home/uchida/.gradle/caches/modules-2/files-2.1/org.jetbrains/annotations/13.0/919f0dfe192fb4e063e7dacadee7f8bb9a2672a9/annotations-13.0.jar MainKt
Server: nginx/1.24.0
Date: Sat, 04 Nov 2023 08:12:47 GMT
Content-Type: application/json
Content-Length: 407
Last-Modified: Sat, 04 Nov 2023 02:02:15 GMT
Connection: keep-alive
ETag: "6545a627-197"
Access-Control-Allow-Origin: *
Accept-Ranges: bytes
[{"id":18,"countryName":"Kenya"},
{"id":20,"countryName":"Tanzania"},
{"id":21,"countryName":"Ethiopia"},
{"id":22,"countryName":"Malawi"},
{"id":23,"countryName":"Country"},
{"id":24,"countryName":"Country"},
{"id":25,"countryName":"Kenya"},
{"id":26,"countryName":"Country"},
{"id":27,"countryName":"USA"},
{"id":28,"countryName":"USA"},
{"id":29,"countryName":"Kenya"},
{"id":30,"countryName":"Kenya"}]
Process finished with exit code 0