본문 바로가기

Java 길찾기/Java의 정석

[Java] URL, URLConnection

URL

URL(Uniform Resource Locator)은 인터넷에 존재하는 여러 서버들이 제공하는 자원에 접근할 수 있는 주소를 표현하기 위한 것으로 

'프로토콜://호스트명:포트번호/경로명/파일명?쿼리스트링#참조' 의 형태로 이루어져 있다.

|참고| URL에서 포트번호, 쿼리, 참조는 생략할 수 있다.

 

http://www.codechobo.com:80/sample/hello.html?referer=codechobo#index1

프로토콜        자원에 접근하기 위해 서버와 통신하는데 사용되는 통신규약(http)
호스트명        자원을 제공하는 서버의 이름(www.codechobo.com)
포트번호        통신에 사용되는 서버의 포트번호(80)
경로명            접근하려는 자원이 저장된 서버상의 위치(/sample/)
파일명            접근하려는 자원의 이름(hello.html)
쿼리(query)    URL에서 '?' 이후의 부분(referer=codechobo)
팜조(anchor)  URL에서 '#' 이후의 부분(index1)

 

자바에서는 URL을 다루기 위한 클래스로 URL클래스를 제공하며 다음과 같은 메서드가 정의되어 있다.

 

메서드 설명
URL(String spec) 지정된 문자열의 정보의 URL 객체를 생성한다. 
URL(String protocol, String host, String file) 지정된 값으로 구성된 URL 객체를 생성한다.
URL(String protocol, String host, int port, String file) 지정된 값으로 구성된 URL 객체를 생성한다.
String getAuthority() 호스트명과 포트를 문자열로 반환한다.
Object getContent() URL의 Content 객체를 반환한다.
Object getContent(Class[] classes) URL의 Content 객체를 반환한다.
int getDefaultPort() URL의 기본 포트를 반환한다.
String getFile() 파일명을 반환한다.
String getHost() 호스트명을 반환한다.
String getPath() 경로명을 반환한다.
int getPort() 포트를 반환한다.
String getProtocol() 프로토콜을 반환한다.
String getQuery() 쿼리를 반환한다.
String getRef() 참조(anchor)를 반환한다.
String getUserInfo() 사용자정보를 반환한다.
URLConnection openConnection() URL과 연결된 URLConnection을 얻는다.
URLConnection openConnection(Proxy proxy) URL과 연결된 URLConnection을 얻는다.
InputStream openStream() URL과 연결된 URLConnection의 InputStream을 얻는다.
boolean sameFile(URL other) 두 URL이 서로 같은 것인지 알려준다.
void set(String protocol, String host, int port, String file, String ref) URL 객체의 속성을 지정된 값으로 설정한다.
void set(String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref) URL 객체의 속성을 지정된 값으로 설정한다.
String toExternalForm() URL을 문자열로 변환하여 반환한다.
URL toURI() URL을 URI로 변환하여 반환한다.

 

URL 객체를 생성하는 방법은 다음과 같다.

 

URL url = new URL("http://www.codechobo.com/sample/hello.html");
URL url = new URL("www.codechobo.com", "/sample/hello.html");
URL url = new URL("http", "www.codechobo.com", 80, "/sample/hello.html");

 

위의 표의 설명보다 예제의 실행결과를 보는 것이 메서드에 대한 이해가 더 빠를 것이다.

 

import java.net.*;

class NetworkEx2 {
   public static void main(String[] args) throws Exception {
       URL url = new URL("http://www.codechobo.com/sample/" + "hello.html?referer=codechobo#index1");

       System.out.println("url.getAuthority() : " + url.getAuthority());
       System.out.println("url.getContent() : " + url.getContent());
       System.out.println("url.getDefaultPort() : " + url.getDefaultPort());
       System.out.println("url.getPort() : " + url.getPort());
       System.out.println("url.getFile() : " + url.getFile());
       System.out.println("url.getHost() : " + url.getHost());
       System.out.println("url.getPath() : " + url.getPath());
       System.out.println("url.getProtocol() : " + url.getProtocol());
       System.out.println("url.getQuery() : " + url.getQuery());
       System.out.println("url.getRef() : " + url.getRef());
       System.out.println("url.getUserInfo() : " + url.getUserInfo());
       System.out.println("url.toExternalForm() : " + url.toExternalForm());
       System.out.println("url.toURI() : " + url.toURI());
   }
}

 

 

URLConnection

URLConnection은 어플리케이션과 URL간의 통신연결을 나타내는 클래스의 최상위 클래스로 추상클래스이다. URLConnection을 상속받아 구현한 클래스로는 HttpURLConnection과 JarURLConnection이 있으며 URL의 프로토콜이 http프로토콜이라면 openConnection()은 HttpURLConnection을 반환한다. URLConnection을 사용해서 연결하고자하는 자원에 접근하고 읽고 쓰기를 할 수 있다. 그 외에 관련된 정보를 읽고 쓸 수 있는 메서드가 제공된다.

|참고| openConnection()은 URL 클래스의 메서드이다.

 

메서드 설명
void addRequestProperty(String key, String value) 지정된 키와 값을 RequestProperty에 추가한다. 기존에 같은 키가 있다면 같은 값을 덮어쓰지 않는다.
void connect() URL에 지정된 자원에 대한 통신연결을 연다.
boolean getAllowUserInteraction() UserInteraction의 허용여부를 반환한다.
int getConnectTimeout() 연결종료시간을 1/1000 초로 반환한다.
Object getContent() content의 객체를 반환한다.
Object getContent(Class[] classes) content의 객체를 반환한다.
String getContentEncoding() content의 인코딩을 반환한다.
int getContentLength() content의 크기를 반환한다.
String getContentType() content의 타입을 반환한다.
long getDate() 헤더의 date필드의 값을 반환한다.
boolean getDefaultAllowUserInteraction() defaultAllowUserInteraction의 값을 반환한다.
String getDefaultRequestProperty(String key) RequestProperty에서 지정된 키의 디폴트값을 얻는다.
boolean getDefaultUserCaches() userCache의 디폴트값을 얻는다.
boolean getDoInput() doInput필드값을 얻는다.
boolean getDoOutput() doOutput필드값을 얻는다.
long getExpiration() 자원(URL)의 만료일자를 얻는다.(1/1000초 단위)
FileNameMap getFileNameMap(0 FileNameMap(mimetable)을 반환한다.
String getHeaderField(int n) 헤더의 n번째 필드를 읽어온다.
Strnig getHeaderField(String name) 헤더에서 지정된 이름의 필드를 읽어온다.
long getHeaderFieldDate(String name, long default) 지정된 필드의 값을 날짜값으로 변환하여 반환한다.
필드값이 유효하지 않을 경우 Default값을 반환한다.
int getHeaderFieldInt(String name, int default) 지정된 필드의 값을 정수값으로 변환하여 반환한다.
필드값이 유효하지 않을 경우 Default값을 반환한다.
String getHeaderFieldKey(int n) 헤더의 n번째 필드를 읽어온다.
Map getHeaderFields() 헤더의 모든 필드와 값이 저장된 Map을 반환한다.
long getIfModifiedSince() ifModifiedSince(변경여부)필드의 값을 반환한다.
InputStream getInputStream() URLConnection에서 InputStream을 반환한다.
long getLastModified() LastModified(최종변경일)필드의 값을 반환한다.
OutputStream getOutputStream() URLConnection에서 OutputStream을 반환한다.
Permission getPermission() Permission(허용권한)을 반환한다.
int getReadTimeout() 일기제한시간의 값을 반환한다.(1/1000 초)
Map getRequestProperties() RequestProperties에 저장된 (키, 값)을 Map으로 변환
String getRequestProperty(String key) RequestProperty에 지정된 키의 값을 반환한다.
URL getURL() URLConnection의 URL을 반환한다.
boolean getUseCaches() 캐쉬의 사용여부를 반환한다.
String guessContentTypeFromName(String fname) 지정된 파일(fname)의 content-type을 추측하여 반환한다.
String guessContentTypeFromStream(InputStream is) 지정된 입력스트림(is)의 content-type을 추측하여 반환한다.
void setAllowUserInteraction(boolean allowuserinteraction) UserInteraction의 허용여부를 설정한다.
void setConnectTimeout(int timeout) 연결종료시간을 설정한다.
void setContentHandlerFactory(ContentHandlerFactory fac) ContentHandlerFactory를 설정한다.
void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) UserInteraction허용여부의 기본값을 설정한다.
void setDefaultRequestProperty(String key, String value) RequestProperty의 기본 키쌍(key-pair)을 설정한다.
void setDefaultUseCaches(boolean defaultusecaches) 캐쉬 사용여부의 기본값을 설정한다.
void setDoInput(boolean doinput) DoInput필드의 값을 설정한다.
void setDoOutput(boolean dooutput) DoOutput필드의 값을 설정한다.
void setFileNameMap(FileNameMap map) FileNameMap을 설정한다.
void setIfModifiedSince(long ifmodifiedsince) ModifiedSince필드의 값을 설정한다.
void setReadTimeout(int timeout) 읽기제한시간을 설정한다.(1/1000 초)
void setRequestProperty(String key, String value) RequestProperty에 (key, value)를 저장한다.
void setUseCaches(boolean usecaches) 캐쉬의 사용여부를 설정한다.

 

import java.net.*;

class NetworkEx3 {
   public static void main(String[] args) throws Exception {
       URL url = null;
       String address = "http://www.codechobo.com/sample/hello.html";
       
       try {
           url = new Url(address);
           URLConnection conn = url.openConnection();

           System.out.println("conn.toString() : " + conn);
           System.out.println("getAllowUserInteration() : " + conn.getAllowUserInteration());
           System.out.println("getContentTimeout() : " + conn.getContentTimeout());
           System.out.println("getContent() : " + conn.getContent());
           System.out.println("getContentEncoding() : " + conn.getContentEncoding());
           System.out.println("getContentLength() : " + conn.getContentLength());
           System.out.println("getContentType() : " + conn.getContentType());
           System.out.println("getDate() : " + conn.getDate());
           System.out.println("getDefaultAllowUserInteraction() : " + conn.getDefaultAllowUserInteraction());
           System.out.println("getDefaultUseCashes() : " + conn.getDefaultUseCashes());
           System.out.println("getDoInput() : " + conn.getDoInput());
           System.out.println("getDoOutput() : " + conn.getDoOutput());
           System.out.println("getExpiration() : " + conn.getExpiration());
           System.out.println("getHeaderFields() : " + conn.getHeaderFields());
           System.out.println("getIfModifiedSince() : " + conn.getIfModifiedSince());
           System.out.println("getLastModified() : " + conn.getLastModified());
           System.out.println("getReadTimeout() : " + conn.getReadTimeout());
           System.out.println("getURL() : " + conn.getURL());
           System.out.println("getUserCaches() : " + conn.getUserCaches());
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}

 

URLConnection을 생성하고 get메서드들을 통해서 관련정보를 얻어서 출력하는 예제이다. 예제의 결과를 보고 어떤 메서드를 통해 어떠한 정보를 얻을 수 있는지 확인해보는 것을 추천한다.

 

import java.net.*;
import java.io.*;

class NetworkEx4 {
   public static void main(String[] args) throws Exception {
       URL url = null;
       BufferedReader input = null;
       String address = "http://www.codechobo.com/sample/hello.html";
       String line = "";

       try {
           url = new Url(address);
           input = new BufferedReader(new InputStreamReader(url.openStream()));

           while((line=input.readLine())!=null){
               System.out.println(line);
           }
           input.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}

 

URL에 연결하여 그 내용을 읽어오는 예제이다. 만일 URL이 유효하지 않으면 Malformed- URLException이 발생한다. 읽어올 데이터가 문자데이터이기 때문에 BufferedReader를 사용하였다. openStream()을 호출해서 URL의 InputStream을 얻은 이후로는 파일로부터 데이터를읽는 것과 다르지 않다.

openStream()은 openConnection()을 호출해서 URLConnection을 얻은 다음 여기에 다시 getInputStream()을 호출한 것과 같다. 즉 URL에 연결해서 InputStream을 얻어온다.

 

import java.net.*;
import java.io.*;

class NetworkEx4 {
   public static void main(String[] args) throws Exception {
       URL url = null;
       inputStream in = null;
       FileOutputStream out = null;
       String address = "http://www.codechobo.com/book/src/javajungsuk3_src.zip";

       int ch = 0;
       
       try {
           url = new Url(address);
           in = url.openStream();
           out = new FileOutputStream("javajungsuk3_src.zip");

           while((ch=in.read())!=-1){
               out.write(ch);
           }
           in.close();
           out.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}

 

이전 예제와 유사한데 텍스트 데이터가 아닌 이진 데이터를 읽어서 파일에 저장한다는 것만 다르다. 그래서 FileReader가 아닌 FileOutputStream을 사용하였다.