네트워킹(Networking) (2) - URL, URLConnection
5. URL (Uniform Resource Locator)
- URL은 인터넷에 존재하는 여러 서버들이 제공하는 자원에 접근할 수 있는 주소를 표현하기 위한 것이다.
- 형식은 '프로토콜://호스트명:포트번호/경로명/파일명?쿼리스트링#참조'의 형태로 이루어져 있다.
( URL에서 포트번호, 쿼리, 참조는 생략가능함. )
- 아래는 URL의 형식에 있는 각 단어의 개념을 설명한다.
(1) 프로토콜
: 자원에 접근하기 위해 서버와 통신하는데 사용되는 통신규약
( ex) HTTP )
(2) 호스트명
: 자원을 제공하는 서버의 이름
( ex) www.dasdw.com )
(3) 포트번호
: 통신에 사용되는 서버의 포트번호
( ex) 80 )
(4) 경로명
: 접근하려는 자언이 저장된 서버상의 위치
( ex) /sample/ )
(5) 파일명
: 접근하려는 자원의 이름
( ex) hello.html )
(6) 쿼리
: URL에서 '?' 이후의 부분
( ex) referer = dasdw )
(7) 참조(anchor)
: URL에서 '#' 이후의 부분
( ex) index1 )
- 자바에서는 URL 다루기 위한 클래스로 URL 클래스를 제공한다.
- 아래는 URL 클래스의 생성자/메서드를 설명한다.
생성자 | 설명 |
URL(String spec) | 지정된 문자열 정보의 URL 객체를 생성한다. |
URL(String protocol, String host, String file) URL(String protocol, String host, int port, String file) |
지정된 값으로 구성된 URL 객체를 생성한다. |
( 생성자 생성하는 방법은 아래의 예시를 통해 이해하자. )
ex1) URL url = new URL("http://www.dasdw.com/sample/hello.html");
ex2) URL url = new URL("www.dasdw.com", "/sample/hello.html");
ex3) URL url = new URL("http", "www.dasdw.com", 80, "/sample/hello.html");
메서드 | 설명 |
String getAuthority() | 호스트명과 포트를 문자열로 반환한다. |
Object getContent() 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() URLConnection openConnection(Proxy proxy) |
URL과 연결된 URLConnection을 얻는다. |
InputStream openStream() | URL과 연결된 URLConnection의 InputStream을 얻는다. |
String toExternalForm() | URL을 문자열로 변환하여 반환한다. |
URL toURL() | URL을 URI로 변환하여 반환한다. |
6. URLConnection
- URLConnection은 어플리케이션과 URL간의 통신연결을 나타내는 클래스의 최상위 클래스로 추상클래스이다.
- URLConnection을 상속받아 구현한 클래스로는 HttpURLConnection과 JarURLConnection이 있다.
( 만약 URL 프로토콜이 http이라면, openConnection()은 HttpURLConnection을 반환한다. )
- 아래는 URLConnection을 이해하기 위한 예제에서 나오는 메서드들을 설명한다.
( URLConnection과 관련된 메서드들은 많기 때문에 자세한 내용은 954p~955p를 참고한다. )
메서드 | 설명 |
boolean getAllowUserInteraction() | UserInteraction의 허용여부를 반환한다. |
int getConnectTimeout() | 연결종료시간을 천분의 일초로 반환한다. |
Object getContent() Object getContent(Class[] classes) |
Content 객체를 반환한다. |
String getContentEncoding() | Content의 인코딩을 반환한다. |
int getContentLength() | Content의 크기를 반환한다. |
int getContentType() | Content의 타입을 반환한다. |
long getDate() | 헤더의 date 필드의 값을 반환한다. |
boolean getDefaultAllowUserInteraction() | dafaultAllowUserInteraction의 값을 반환한다. |
boolean getDefaultUserCaches() | useCache의 디폴트 값을 얻는다. |
boolean getDoInput() | doInput 필드값을 얻는다. |
boolean getDoOutput() | doOutput 필드값을 얻는다. |
Map getHeaderFields() | 헤더의 모든 필드와 값이 저장된 Map을 반환한다. |
long getIfModifiedSince() | ifModifiedSince(변경여부) 필드의 값을 반환한다. |
long getLastModified() | LastModified (최종변경일) 필드의 값을 반환한다. |
int getReadTimeout() | 읽기제한시간의 값을 반환한다. (1/1000초) |
URL getURL() | URLConnection의 URL의 반환한다. |
boolean getUseCaches() | 캐쉬의 사용여부를 반환한다. |
6-1 URLConnection을 이해하기 위한 예제(1)
: 간단하게 네이버 국어사전을 들어가서 메서드를 통해 정보를 받아온 예제이다.
package Networking;
import java.net.URL;
import java.net.URLConnection;
public class Exercise003 {
public static void main(String[] args) {
URL url = null;
String address = "https://ko.dict.naver.com/#/main";
String line = "";
try {
url = new URL(address);
URLConnection conn = url.openConnection();
System.out.println("conn.toString():"+conn);
System.out.println("getAllowUserInteraction():"+conn.getAllowUserInteraction());
System.out.println("getConnectTimeout():"+conn.getConnectTimeout());
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("getDefaultUseCaches():"+conn.getDefaultUseCaches());
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("getUseCaches():"+conn.getUseCaches());
} catch(Exception e) {
e.printStackTrace();
}
}
}
( getHeaderFields() 를 통해 자신이 원하는 필드값을 가질 수 있다. )
( 또한 크롬 또는 마이크로 엣지 유저는 F12를 통해 값의 필드 값을 알 수 있다. )
6-2. URLConnection을 이해하기 위한 예제(2)
: URL에 연결하여 그 내용을 읽어오는 예제이다.
package Networking;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class Exercise004 {
public static void main(String[] args) {
URL url = null;
BufferedReader input = null;
String address = "https://ko.dict.naver.com/#/main";
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이 유효하지 않으면 Malformed- URLException이 발생한다. )
( 읽어올 데이터가 문자데이터이기 때문에 BufferedReader를 사용하였다. )
( openStream()을 호출해서 URL의 InputStream을 얻은 이후로는 파일로부터 데이터를 읽는 것과는 다르지 않다. )
InputStream in = url.openStream();
또는
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
6-3. URLConnection을 이해하기 위한 예제(3)
: 이전 예제와 유사하게 텍스트 데이터가 아닌 이진 데이터를 읽어서 파일을 저장한다는 것만 다른 예제이다.
package Networking;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Exercise005 {
public static void main(String args[]) {
URL url = null;
InputStream in = null;
FileOutputStream out = null;
String address = "https://ko.dict.naver.com/#/main";
int ch = 0;
try {
url = new URL(address);
in = url.openStream();
out = new FileOutputStream("URLConnectionFile.zip");
while((ch=in.read()) !=-1) {
out.write(ch);
}
in.close();
out.close();
} catch(Exception e) {
e.printStackTrace();
}
} // main
}
( 이진 데이터를 위해 FileReader(텍스트 기반)가 아닌 FileOutputStream을 사용하였다. )