자바
URL 클래스
devjones
2020. 9. 6. 16:09
URL 형식
프로토컬://호스트:포트//경로/리소스 이름
URL 클래스의 메소드들 중 openStream() 메소드를 사용하면 인터넷을 통해 리소스를 읽거나 쓸 수 있다. 다음은 openStream() 메소드를 이용해서 URL로부터 직접 정보를 읽어오는 예제이다. openStream() 메소드는 InputStream형 객체를 돌려주는데, 이를 다음 예제처럼 BufferedReader() 메소드의 인수로 넘겨주면 된다.
package ch03;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest {
public static void main(String[] args) {
String str;
try {
URL myURL = new URL("https://www.kt.com");
BufferedReader in = new BufferedReader(new InputStreamReader(myURL.openStream()));
while((str = in.readLine()) != null) {
System.out.println(str);
}
} catch (MalformedURLException e) {
System.out.println(e.toString());
} catch (IOException e) {
System.out.println(e.toString());
}
}
}