프로그램/Java

[Java] HttpsURLConnection에서 한글 깨짐 현상 해결 방법

neorc 2025. 5. 20. 10:54
Java로 HTTPS 요청을 보내다 보면, JSON이나 텍스트 데이터를 주고받을 때 한글이 깨지는 문제를 종종 경험하게 됩니다. 저도 초기에 API를 연동하면서 "홍길동"이라는 문자열이 서버에 도착했을 때 ì´ˆê¸°ì „처럼 깨지는 걸 보고 당황했던 기억이 납니다.
그렇다면 이 현상은 왜 생기며, 어떻게 해결할 수 있을까요?

 

한글 깨짐 원인은?

가장 큰 이유는 인코딩 설정 누락입니다.
Java에서는 기본적으로 ISO-8859-1 인코딩을 사용하는 경우가 있기 때문에, 명시적으로 UTF-8을 지정하지 않으면 한글이 깨질 수 있습니다.

또한 서버와 클라이언트 간의 통신에서는 요청(Request)과 응답(Response) 모두에서 인코딩이 중요합니다. 하나라도 빠지면 문제가 발생합니다.

 

해결 방법 ①: Content-Type 헤더에 charset 설정

요청을 보낼 때, 아래와 같이 charset=UTF-8을 반드시 포함해줘야 합니다.

conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

 

서버가 이 정보를 기준으로 데이터를 UTF-8로 해석하게 됩니다.

해결 방법 ②: 데이터 전송 시 UTF-8 인코딩

OutputStream에 데이터를 쓸 때도 UTF-8로 변환해 줘야 합니다.

String jsonInput = "{\"name\":\"홍길동\"}";
try (OutputStream os = conn.getOutputStream()) {
    byte[] input = jsonInput.getBytes("UTF-8");
    os.write(input, 0, input.length);
}

해결 방법 ③: 응답 읽기 시 UTF-8 디코딩

서버로부터 응답을 받을 때도 InputStreamReader에 UTF-8을 지정해 주세요.

try (BufferedReader br = new BufferedReader(
    new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        response.append(line.trim());
    }
    System.out.println("Response: " + response);
}

 

실제 코드 예제 (전체 흐름)

URL url = new URL("https://example.com/api");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");

String jsonInput = "{\"name\":\"홍길동\"}";
try (OutputStream os = conn.getOutputStream()) {
    byte[] input = jsonInput.getBytes("UTF-8");
    os.write(input, 0, input.length);
}

try (BufferedReader br = new BufferedReader(
    new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        response.append(line.trim());
    }
    System.out.println("Response: " + response);
}

 

HttpsURLConnection에서 한글이 깨질 땐 항상 UTF-8 인코딩 설정을 두 번 확인하세요.

  • 요청 헤더에 charset=UTF-8 포함하기
  • OutputStream과 InputStreamReader에 UTF-8 명시하기

이 기본적인 원칙만 잘 지키면, 한글 깨짐 없이 안정적인 통신이 가능합니다!