안규 공부방

Android > HttpURLConnection - getContentType() 한글 인코딩 (UTF-8, EUC-KR)

등록일 : 2017-07-06 17:36 조회수 : 68,498

웹과 관련된 프로그램을 구성할 때, URL을 입력해서 해당 글을 가져오는 루틴이 필요한 경우가 종종 있습니다.

이 경우, 항상 문제가 되는 것이 바로 인코딩 문제인데요.

웹사이트의 경우, 인코딩을 주로 UTF-8과 EUC-KR의 두 가지를 사용해서 처리하고 있습니다.

헤더정보만 읽어와서 인코딩을 파악하는 방식을 소개하고자 합니다.
 
	URL u = new URL(strUrl);
	URLConnection uc = u.openConnection();
	String headerType = uc.getContentType();

	BufferedReader in;
		
	if (headerType.toUpperCase().indexOf("EUC-KR") != -1) {
		in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"EUC-KR"));
	} else if (headerType.toUpperCase().indexOf("UTF-8") != -1){
		in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));
	}
	


소스를 보면 ContentType을 가져오는 부분이 있습니다.
여기에 UTF-8인지 EUC-KR인지 정보가 포함되어 있는지를 확인하고 해당 인코딩으로 문서를 읽어오는 것입니다.

이왕 정리한 것 URL을 문자열로 주면 해당 HTML을 모두 읽어와서 리턴해주는 함수를 올립니다.

ContentType에 인코딩 정보가 없을 경우도 EUC-KR로 선정하도록 코딩했습니다.
 
	private String getUrlContent(String strUrl) throws Exception {
		URL u = new URL(strUrl);
		URLConnection uc = u.openConnection();

		uc.setDoOutput(true);
		uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		
		String headerType = uc.getContentType();
		
		BufferedReader in;
		if (headerType.toUpperCase().indexOf("UTF-8") != -1){
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));
		} else {
			in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"EUC-KR"));
		}

		StringBuffer sb = new StringBuffer();
		String thisLine = null;
		while( (thisLine = in.readLine())!=null ){
			sb.append(thisLine);
			sb.append("\n");
		}
		in.close();		
		
		return sb.toString();
	}
	
 
※ 혹시 도움이 되셨다면 댓글에 한마디 남겨주세요!
작성자   비밀번호
자동글 방지     (자동글 방지 기능입니다.)
내용   댓글달기 
이메일 문의 : cak0280@nate.com  
Copyright 2000 By ENTERSOFT.KR All Rights Reserved.