본문 바로가기

컴퓨터/android

HTML 읽기

 String downloadURL(String addr) {

String doc = "";

try {

URL url = new URL(addr);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

if (conn != null) {

conn.setConnectTimeout(10000);

conn.setUseCaches(false);

if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 연결이

                 // 완성이됫다

BufferedReader br = new BufferedReader(

new InputStreamReader(conn.getInputStream()));

for (;;) {

String line = br.readLine();

if (line == null)

break;

doc = doc + line + "\n";

}

br.close();

}

conn.disconnect();

}

catch (Exception ex) {;}

return doc;

 }


인수로 전달받은 주소로부터 URL 객체 생성 openConnection 메서드로 연결

연결 타임 아웃은 10초로 지정

캐시는 사용 안 함

getResponse 메서도로 요청을 보냄

요사히 전달시 HTTP_OK(200) 리턴, URL이 발견되지 않으면 HTTP_NOT_FOUND(404) 리턴, 

인증에 실패하면 HTTP_UNAUTHORIZED(401) 에러코드 리턴

요청 성공시 getInputStream 메서드로 입력 스트림을 얻어 서버로부터 전송된 결과를 읽어 들임

스트림을 직접 읽으면 느리고 비효율적이어서 버퍼를 지원하는 보조 스트림 객체로 감싸서 사용(BufferedReader)