개발/Java
Java - 연결된 url로부터 데이터 읽기
뉴에이스
2018. 10. 2. 17:11
소스
public static void test01() {
try {
/*
기본 80번 포트로 접속해서 index.html, index.htm, index.jsp를 찾는다.
url 정보를 html로 바이트단위로 보내기 때문에 InputStream으로 받고, 한글을 정상적으로 읽기 위해서는 InputReader를 사용한다.
*/
URL url = new URL("https://www.daum.net");
InputStream in = url.openStream();
while(true) {
int ch = in.read();
if(ch == -1) break;
System.out.print((char)ch);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void test02() {
try {
URL url = new URL("https://www.daum.net");
InputStream in = url.openStream();
byte[] buffer = new byte[1024*16];
while(true) {
int ch = in.read(buffer);
if(ch == -1) break;
// buffer의 0번째 배열부터 ch까지를 utf-8 방식으로 조합해서 string으로 변환
String data = new String(buffer, 0, ch, "utf-8");
System.out.print(data);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void test03() {
try {
URL url = new URL("https://www.daum.net");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
while(true) {
String line = br.readLine();
if(line == null) break;
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
결과
<!DOCTYPE html>
<html lang="ko" class="">
<head>
.
.
.
</body>
</html>