[JAVA] writer 사용하여 HTML 파일 리턴시 내용 증발

Posted by 김성철

JAVA - writer 사용하여 HTML 파일 리턴시 내용 증발

증상

Body에 내용들을 전부다 추가하고 writer 로 데이터를 리턴하는데,, 분명 내가 적은 내용들이 전부다 리턴이 안됨  

원본 코드

=====================================================================  
this.writer.write(responseCode + "\r\n");  
this.writer.write("Date: " + DateUtil.getTime("yyyy-MM-dd HH:mm:ss") + "\r\n");  
this.writer.write("Server: JHTTP 2.0\r\n");  
this.writer.write("Content-length: " + contentLength + "\r\n");  
this.writer.write("Content-type: " + contentType + "\r\n\r\n");  
this.writer.write(body);  
this.writer.flush();  
=====================================================================   ## 리턴할 내용  
=====================================================================  
<!DOCTYPE html>  
<meta charset="UTF-8">  
<html lang="en">  
<head>  
	<meta charset="UTF-8">  
	<title>Title</title>  
</head>  
<body>  
B HOST Index.html<br>  
bhost.com , bhost.co.kr 등 bhost로 시작하는 도메인 접속 시 해당 페이지로 연결됩니다.  
</body>  
</html>  
=====================================================================  

리턴된 내용

=====================================================================  
<!DOCTYPE html>  
<meta charset="UTF-8">  
<html lang="en">  
<head>  
	<meta charset="UTF-8">  
	<title>Title</title>  
</head>  
<body>  
B HOST Index.html<br>  
bhost.com , bhost.co.kr 등 bhost로 시작하는 도메인 접속 시 해  
=====================================================================  

분석

데이터가 중간에 끊긴 이유는 HTTP 응답 헤더의 Content-length 값을 body.length(); 로 지정했음  
body.length()는 문자열의 길이를 반환하는 메소드로 문자열 길이와 바이트 수가 일치하지 않을 수 있음  
전송되는 데이터에 한글이 포함되어 있는 경우 길이와 바이트가 다를수 있음  

해결

body에 있는 데이터를 byte로 변환하여 전송  
=====================================================================  
byte[] responseBody = body.getBytes(StandardCharsets.UTF_8);  
int contentLength = responseBody.length;  
write("Content-length: " + contentLength + "\r\n");  
=====================================================================