PHpullh

LANGUAGE COMPARISON

HTTP를 언어별로 비교하기

같은 개념을 실제 예제로 나란히 확인하고, 각 언어의 개별 설명으로 이어갈 수 있습니다.

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

Python

httpx 비동기 HTTP 클라이언트

requests 대체, async with AsyncClient 패턴

<span class="cm">// httpx 비동기 HTTP 클라이언트 예제
// data/prompts.js의 생성 프롬프트로 상세 코드 생성 가능</span>
fun main() { println("httpx 비동기 HTTP 클라이언트") }

Go

net/http ServeMux 개선 (1.22+)

메서드 패턴, 와일드카드 라우팅 지원

<span class="cm">// net/http ServeMux 개선 (1.22+) 예제
// data/prompts.js의 생성 프롬프트로 상세 코드 생성 가능</span>
fun main() { println("net/http ServeMux 개선 (1.22+)") }

Java

HTTP Client (java.net.http)

Java 11+의 내장 HTTP 클라이언트로 REST API를 호출합니다.

import java.net.http.*;
import java.net.URI;
import java.time.Duration;

public class HttpClientDemo {
    public static void main(String[] args) throws Exception {
        // HttpClient 생성 (재사용 권장)
        HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(10))
            .followRedirects(HttpClient.Redirect.NORMAL)
            .build();

        // GET 요청
        HttpRequest getReq = HttpRequest.newBuilder()
            .uri(URI.create("https://httpbin.org/get"))
            .header("Accept", "application/json")
            .timeout(Duration.ofSeconds(30))
            .GET()
            .build();

        HttpResponse<String> response = client.send(
            getReq, HttpResponse.BodyHandlers.ofString());
        System.out.println("상태: " + response.statusCode());
        System.out.println("본문: " + response.body().substring(0, 100));

        // POST 요청
        String json = "{\"name\":\"test\",\"value\":42}";
        HttpRequest postReq = HttpRequest.newBuilder()
            .uri(URI.create("https://httpbin.org/post"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();

        // 비동기 요청
        client.sendAsync(postReq, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenAccept(body -> System.out.println("비동기: " + body.length()))
            .join();
    }
}

PHP

curl_multi 로 병렬 요청

가벼운 병렬 HTTP 호출이 필요할 때 가장 먼저 떠올릴 수 있는 curl_multi 예제입니다.

<?php
$urls = ['https://example.com', 'https://example.org'];
$multi = curl_multi_init();
$handles = [];

foreach ($urls as $url) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 3,
    ]);
    curl_multi_add_handle($multi, $ch);
    $handles[] = $ch;
}

do {
    curl_multi_exec($multi, $running);
    curl_multi_select($multi);
} while ($running > 0);

echo count($handles);