- 프로토콜의 상세사항, 서버와 통신 방법에 관해 염려할 필요가 없고 자바에게 URL 을 전달함으로써 데이터를 얻는다.
Protocol(Scheme)
- 서버의 자원에 접근하는 방법으로 무슨 프로토콜을 사용할 것인가
- scheme : URI 의 RFC 에서 사용하는 용어
- protocol : 자바 문서에서 사용하는 용어
host
- 자원을 제공하는 서버 이름
사용자 정보 (User ID 와 Password)
- 선택사항
port
- Optional
기관 (Authority)
- 사용자 정보 (user id:password) + 호스트 + 포트
경로
- 지정된 서버의 특정 자원
파라미터
- 일부의 Scheme 이 자원에 접근할 때 필요한 부가적인 정보 (가령 ftp에서 자료 전송을 binary 모드로 할 것인가 text 모드로 할 것인가)
질의 문자열 (query)
- http URL 에서만 쓰임
문서 위치 (Fragment Identifier)
- 자원의 특정 부분을 가리킴
http://www.ibiblio.org/javafaq/javatutorial.html
- 프로토콜 (= scheme) : http
http://metalab.unc.edu/javafaq/books/jnp/index.jsp?isdn=1565922069#toc
- 프로토콜 : http
URL 은 문서에 관해 웹 브라우저에 알리는 것
- 문서검색 프로토콜, 문서가 위치한 컴퓨터, 문서까지의 경로
이런 정보의 대부분은 문서에서 참조되는 다른 URL과 일치하기 마련
따라서 전체를 나타내는 것보다 부모 문서 (문서가 들어있는 문서) 의 프로토콜, 호스트, 경로 등을 상속하도록 하는 것이 유리하다.
예 :
- http://metalab.unc.edu/javafaq/javatutorial.html 문서를 browsing 하다가 라는 hyperlink를 발견했다면 이것이 상대 URL 이며 절대 URL은 http://metalab.unc.edu/javafaq/ + javafaq.html 이다.
- / 로 시작하는 상대 URL 은 현 문서에 상대적인 것이 아니라 문서 루트에 상대적
- 동일 문서 속에서 이라는 하이퍼링크를 만나면 절대 URL 은 http://metalab.unc.edu + /boutell/faq/www_faq.html
try{
URL u = new URL("http://www.jnu.ac.kr");
}
catch(MalformedURLException e) {
System.err.println(e);
}
import java.net.*;
public class ProtocolTester {
public static void main(String[] args) {
// hypertext transfer protocol
testProtocol("http://www.adc.org");
// secure http
testProtocol("https://www.amazon.com/exec/obidos/order2/");
// file transfer protocol
testProtocol("ftp://ibiblio.org/pub/languages/java/javafaq/");
// Simple Mail Transfer Protocol
testProtocol("mailto:elharo@ibiblio.org");
// telnet
testProtocol("telnet://dibner.poly.edu/");
// local file access
testProtocol("file:///etc/passwd");
// gopher
testProtocol("gopher://gopher.anc.org.za/");
// Lightweight Directory Access Protocol
testProtocol(
"ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US?postalAddress");
// JAR
testProtocol(
"jar:http://cafeaulait.org/books/javaio/ioexamples/javaio.jar!"
+ "/com/macfaq/io/StreamCopier.class");
// NFS, Network File System
testProtocol("nfs://utopia.poly.edu/usr/tmp/");
// a custom protocol for JDBC
testProtocol("jdbc:mysql://luna.ibiblio.org:3306/NEWS");
// rmi, a custom protocol for remote method invocation
testProtocol("rmi://ibiblio.org/RenderEngine");
// custom protocols for HotJava
testProtocol("doc:/UsersGuide/release.html");
testProtocol("netdoc:/UsersGuide/release.html");
testProtocol("systemresource://www.adc.org/+/index.html");
testProtocol("verbatim:http://www.adc.org/");
}
private static void testProtocol(String url) {
try {
URL u = new URL(url);
System.out.println(u.getProtocol() + " is supported");
} catch (MalformedURLException ex) {
String protocol = url.substring(0, url.indexOf(':'));
System.out.println(protocol + " is not supported");
}
}
}
try {
URL u = new URL("http", "www.eff.org", "/blueribbon.html#intro");
} catch (MalformedURLException e) {
System.err.println(e);
}
상대 URL 과 베이스 URL 을 이용하여 절대 URL 객체 생성
이 생성자는 이미 다른 생성자를 통해 만들어진 베이스 URL 에 불완전한 형태의 상대 URL 을 보태 절대 URL 을 만들어 낸다.
public URL (URL base, String relative) throws MalformedURLException
try {
URL u1 = new URL("http://metalab.unc.edu/javafaq/index.html");
URL u2 = new URL(u1, "mailinglist.html");
} catch (MalformedURLException e) {
System.err.println(e);
}
u1 객체의 경로에서 파일 이름을 빼고 새로운 파일 이름 보충
사용 예
- Loop 를 이용하여 어떤 특정 디렉토리 내의 모든 파일을 처리하고자 할 때
URL u1 = new URL("http://metalab.unc.edu/javafag/index.html");
URL u2 = new URL(u1, "/mailinglist.html");
System.out.println(u2);
URL u3 = new URL("http://A/B/C/index.html");
URL u4 = new URL(u3, "/mailinglist.html");
System.out.println(u4);
URL u5 = new URL("http://A/B/index.html");
URL u6 = new URL(u5, "A/B/mailinglist.html");
System.out.println(u6);
http://metalab.unc.edu/mailinglist.html
http://A/mailinglist.html
http://A/B/A/B/mailinglist.html
getDocumentBase(), getCodeBase()
- getDocumentBase(), getCodeBase() 는 java.applet.Applet에 속한 메소드
DocumentBase
- 애플릿을 내포한 HTML 파일이 들어 있던 디렉토리
CodeBase
- 애플릿이 들어 있던 디렉토리
Java.applet.Applet
- URL getDocumentBase();
java.io.File
- URL toURL()
- 주어진 파일에 해당하는 URL 리턴
- Windows 에서 처리하더라도 file:/D:/JAVA/JNP2/07/ToURLTest.java 형태로 \ 가 아닌 /가 사용됨에 유의
ClassLoader
- URL getSystemResource(String name);
java.swing.Jeditpane
- URL getPage();
java.net.URLCollection
- URL getURL();
- telnet kr.yahoo.com 80 을 입력한다.
- GET / 입력하고 엔터를 친다.
- 키보드로 입력할 때 입력하는 문자가 보이지 않을 수 있다.
- 해당 웹서버의 HTML 태그가 출력된다.
url 이 가리키는 파일 내용을 있는 그대로 읽어 들이고, HTTP 헤더나 프로토콜 관련 다른 정보를 얻는 것은 포기하는 것을 의미한다.
예제 :
try {
URL u = new URL ("http://www.lolcats.com");
InputStream in = u.openStream();
int c;
while((c = in.read() != -1 ) System.out.write(c);
} catch (IOException e) {
System.err.println(e);
}
InputStream in = null;
try {
URL u = new URL(http://www.lolcats.com));
in = u.openStream();
int c;
while ((c = in.read()) != -1) System.out.write( c);
} catch (IOException ex) {
System.err.println(ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
try {
URL u = new URL(http://www.lolcats.com));
try (InputStream in = u.openStream()) {
int c;
while ((c = in.read()) != -1) System.out.write( c);
}
} catch (IOException ex) {
System.err.println(ex);
}
import java.io.*;
import java.net.*;
public class SourceViewer {
public static void main (String[] args) {
if (args.length > 0) {
InputStream in = null;
try {
// Open the URL for reading
URL u = new URL(args[0]);
in = u.openStream();
// buffer the input to increase performance
in = new BufferedInputStream(in);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
} catch (MalformedURLException ex) {
System.err.println(args[0] + " is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
}
<!DOCTYPE html>
<html lang="ko" xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=10.0; user-scalable=1;" /><title>
?쟾?궓???븰援먯뿉 ?삤?떊 寃껋쓣 ?솚?쁺?빀?땲?떎.
</title><link rel="icon" href="/images/favicon.ico" /><link rel="stylesheet" href="/css/font.css" type="text/css" /><link rel="stylesheet" href="/css/common.css" type="text/css" /><link rel="stylesheet" href="/css/layout.css?v=20190930" type="text/css" /><link rel="stylesheet" href="/css/contents.css" type="text/css" /><link rel="stylesheet" href="/common/js/jquery-ui/themes/smoothness/jquery-ui.min.css" />
<script type="text/javascript" src="/Common/js/jquery.min.js"></script>
<script type="text/javascript" src="/Common/js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="/Common/js/jquery-ui/jquery-ui.min.js"></script>
<script type="text/javascript" src="/Common/js/common.js"></script>
<script type="text/javascript" src="/Common/js/common_kr.js"></script>
<link rel="stylesheet" href="/css/home.css" type="text/css" />
<link rel="stylesheet" href="/Common/plugin/slick/css/slick.css" type="text/css" />
<link rel="stylesheet" href="/Common/plugin/slick/css/slick-theme.css" type="text/css" />
public class URLDownload {
public static void main(String args[]) {
try {
URL u = new URL("file://localhost/D:/Work2/JAVA/Test용코드/Network/index.html");
// URL u = new URL("file:///D:/Work2/JAVA/Test용코드/Network/index.html");
Reader r = new InputStreamReader(new BufferedInputStream(u.openStream()));
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
} catch (MalformedURLException e) {
System.err.println(args[0] + " is URL(X)");
} catch (IOException e) {
System.err.println(e);
e.printStackTrace();
}
}
}
try{
URL u = new URL("http://www.hamsterdance.com");
try {
URLConnection uc = u.openConnection();
InputStream in = uc.getInputStream();
// read from the connection .....
} catch (IOException e) {
System.err.println(e);
} catch(MalformedURLException e) {
System.err.println(e):
}