Kotlin
네트워크 I/O (기본)
Java의 HttpURLConnection 과 Kotlin 확장으로 기본적인 HTTP 요청을 수행합니다.
import java.net.HttpURLConnection
import java.net.URL
fun httpGet(urlStr: String): Result<String> = runCatching {
val url = URL(urlStr)
val conn = url.openConnection() as HttpURLConnection
conn.apply {
requestMethod = "GET"
connectTimeout = 5000
readTimeout = 5000
setRequestProperty("Accept", "application/json")
}
try {
if (conn.responseCode == 200) {
conn.inputStream.bufferedReader().use { it.readText() }
} else {
throw RuntimeException("HTTP ${conn.responseCode}: ${conn.responseMessage}")
}
} finally {
conn.disconnect()
}
}
fun httpPost(urlStr: String, body: String): Result<String> = runCatching {
val conn = URL(urlStr).openConnection() as HttpURLConnection
conn.apply {
requestMethod = "POST"
doOutput = true
setRequestProperty("Content-Type", "application/json")
}
conn.outputStream.use { it.write(body.toByteArray()) }
conn.inputStream.bufferedReader().use { it.readText() }
}
fun main() {
httpGet("https://httpbin.org/get").fold(
onSuccess = { println("응답: ${it.take(200)}...") },
onFailure = { println("오류: ${it.message}") }
)
}