시소당
URL은 앞에서 Java2D와 애플릿 장에서 이미지를 처리할 때 설명되었었다. URL은 프로토콜, 포트번호, 호스트, 파일이름 등을 가진다.
URL의 구성
예
프로토콜(서비스의 종류)
http, ftp
포트 번호
80, 21
호스트(도메인)
java.sun.com
파일 이름
index.html, image.gif
URL 클래스의 멤버를 살펴보자.
☞ URL 클래스의 유용한 생성자
public URL(String protocol, String host, int port, String file)
프로토콜, 호스트, 포트, 파일로 구성된 URL 객체를 만든다.
public URL(String protocol, String host, String file)
프로토콜, 호스트, 파일로 구성된 URL 객체를 만든다. 기본 포트를 사용한다.
public URL(String spec)
spec 문자열로 URL 객체를 만든다.
public URL(URL context, String spec)
URL context와 spec으로 구성된 URL 객체를 만든다.
☞ URL 클래스의 유용한 메소드
public String getProtocol()
프로토콜을 문자열로 반환한다.
public String getHost()
호스트 이름을 반환한다.
public String getPath()
경로를 반환한다.
public String getFile()
파일 이름을 반환한다.
public int getPort()
포트 번호를 반환한다.
public URLConnection openConnection() throws java.io.IOException
URL 객체의 URLConnection 객체를 반환한다.
public final InputStream openStream() throws java.io.IOException
URL 객체의 입력 스트림을 반환한다.
URL 객체의 openStream 메소드를 이용하면 웹에 있는 웹 페이지를 쉽게 불러올 수 있다.
URL url=new URL("http://java.sun.com");
InputStream in=new url.onpenStream();
...
실제로 웹 페이지를 읽어오는 예제를 만들어 보자.
[그림 21-14] 웹 페이지 불러오기
PageViewer.java
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
public class PageViewer extends Frame {
private TextField tURL=new TextField(""); // URL을 입력하는 텍스트필드
// 웹 페이지의 소스를 보여주는 텍스트영역
private TextArea tPage=new TextArea();
private BufferedReader reader; // 입력 스트림
public PageViewer(String title){ // 생성자
super(title);
tPage.setEditable(false);
add(tURL,"North");
add(tPage,"Center");
// tURL의 액션 이벤트 처리
tURL.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try{
// tURL의 내용에 해당하는 URL 객체가 참조하는 웹 페이지를 읽는다.
readPage(new URL(tURL.getText()));
}catch(MalformedURLException ie){
tPage.setText("URL이 잘못되었습니다.");
}
}
});
}
// url 객체가 참조하는 웹 페이지를 읽어오는 메소드
void readPage(URL url){
tPage.setText("");
String line;
try{
// url의 입력 스트림을 얻는다.
reader=new BufferedReader(new InputStreamReader(url.openStream()));
// 한 줄 단위로 읽어서 tPage에 추가한다.
while((line=reader.readLine())!=null)
tPage.append(line+"\n");
}catch(IOException ie){
tPage.setText("입출력 예외가 발생하였습니다.");
}finally{
try{
if(reader!=null)reader.close();
}catch(Exception e){}
}
}
public static void main(String[] args){
PageViewer me=new PageViewer("Page Viewer");
me.setSize(400,400);
me.setVisible(true);
}
}
출처 : http://java.pukyung.co.kr/Lecture/Chapter21.php