
HTTP 연결을 통하여 인터넷 파일을 읽기
- URL 클래스의 객체를 생성한다.
- URL 객체를 이용해서 연결하기 위하여 URLConnection 객체를 생성한다.
- URLConnection 객체의 getInputStream() 메서드를 호출하여서 입력 스트림을 얻는다.
- 스트림에서 데이터를 읽는다.
데이터를 읽어서 콘솔에 표시하는 프로그램 코드
- 프로그램 코드
package ex17;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL site = new URL("https://www.naver.com/");
URLConnection url = site.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(url.getInputStream()));
String inLine;
while ((inLine = in.readLine()) != null) {
System.out.println(inLine);
}
in.close();
}
}
출력 결과

네트워크 통신에는 항상 오류 가 발생 할 수 있다!
이로 인해 메서드가 예외를 던지거나, try-catch 구조를 사용하여 예외를 잡거나 해야 한다!
Share article