프로그램/Java

[Java] HttpsURLConnection을 사용할 때 한글이 깨지는 현상

neorc 2025. 5. 20. 10:50
Java에서 HttpsURLConnection 을 사용할 때 한글이 깨지는 현상은 주로 요청(Request) 또는 응답(Response)에서 인코딩 설정이 올바르지 않을 때 발생합니다.

 

  원인: 인코딩 설정 누락

  • 서버에 데이터를 보낼 때 (OutputStream) → UTF-8로 인코딩하지 않으면 한글이 깨짐
  • 서버에서 응답 받을 때 (InputStreamReader) → UTF-8로 디코딩하지 않으면 한글이 깨짐
  • 또한 Content-Type 헤더에 charset=utf-8 설정이 빠져있으면, 서버가 잘못된 문자셋으로 해석할 수 있음

  해결 방법

아래 코드를 참고해서 인코딩 관련 설정을 추가

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

// 요청 본문 전송 시 UTF-8 인코딩
String jsonInput = "{\"name\":\"홍길동\"}";
try (OutputStream os = conn.getOutputStream()) {
    byte[] input = jsonInput.getBytes("UTF-8");
    os.write(input, 0, input.length);
}

// 응답 읽기 시에도 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);
}

 

✅ 추가 팁

  • 서버가 응답 헤더에 charset을 설정하지 않는 경우, 클라이언트에서 강제로 UTF-8로 읽어야 합니다.
  • 혹시 application/x-www-form-urlencoded 방식이라면, URLEncoder.encode("홍길동", "UTF-8")처럼 한글 값을 직접 인코딩해 주세요.

  결론

HttpsURLConnection에서 한글이 깨지는 문제는 대부분 UTF-8 인코딩/디코딩 누락 때문입니다.
setRequestProperty("Content-Type", "application/json; charset=UTF-8") 설정과
InputStreamReader(..., "UTF-8") 를 꼭 확인!