PHpullh
학습 라이브러리/Kotlin/네트워크 I/O (기본)

KOTLIN · 파일/IO

네트워크 I/O (기본)

Java의 HttpURLConnection과 Kotlin 확장으로 기본적인 HTTP 요청을 수행합니다.

파일/IO중급httpnetworkhttpURLConnectionrest

핵심 설명

Java의 HttpURLConnection과 Kotlin 확장으로 기본적인 HTTP 요청을 수행합니다.

Kotlin code

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}") }
    )
}

학습 팁

use 블록으로 스트림을 감싸면 예외 발생 시에도 자동으로 닫힙니다. 리소스 누수를 방지하는 핵심 패턴입니다.

주의할 점

disconnect()를 호출하지 않으면 커넥션이 풀에 반환되지 않아 리소스가 고갈될 수 있습니다. finally 블록에서 반드시 호출하세요.

자주 묻는 질문

네트워크 I/O (기본)란 무엇인가요?

Java의 HttpURLConnection 과 Kotlin 확장으로 기본적인 HTTP 요청을 수행합니다.

네트워크 I/O (기본) 학습 시 주의할 점은 무엇인가요?

disconnect() 를 호출하지 않으면 커넥션이 풀에 반환되지 않아 리소스가 고갈될 수 있습니다. finally 블록에서 반드시 호출하세요.

Continue Learning

Kotlin 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.