sitelink1 | http://whiteship.tistory.com/1137 |
---|---|
sitelink2 | http://whiteship.tistory.com/1165 |
sitelink3 | |
sitelink4 | |
sitelink5 | |
sitelink6 |
참조 : http://java.sun.com/docs/books/tutorial/networking/urls/index.html
What Is a URL?
Uniform Resource Locator의 약자로 인터넷에 있는 자원(Resource)를 의미합니다.
Protocol identifier는 자원을 가져올 때 사용할 프로토콜을 나타냅니다.
Resource Name은 자원의 주소를 나타내며, 보통 다음과 같은 구성요소로 이루어져있습니다.
Host Name, File Name, Port Number, Reference
Creating a URL
일반 객체를 생성하듯이 new 키워드를 사용합니다.
URL gamelan = new URL("http://www.gamelan.com/);
상대경로는 다음과 같이 사용할 수 있습니다.
URL("URL baseURL, String relativeURL)
예를 들어, 다음과 같은 두 개의 URL에 상대경로가 있다고 가정하겠습니다.(실제로 있을지도;;)
http://www.gamelan.com/pages/Gamelan.game.html
http://www.gamelan.com/pages/Gamelan.net.html
이 때 위의 두 URL에 다음과 같이 상대경로로 접근할 수 있습니다.
URL gamelan = new URL("http://www.gamelan.com/pages/);
URL gamelanGames = new URL("gamelan, "Gamelan.game.html");
URL gamelanNetwork = new URL("gamelan, "Gamelan.net.html");
URL addresses with Special characters
URL에 특수 문자(예, 빈칸)가 있을 때는 URI를 사용한다음에 이것을 URL로 변환하면 URI에서 알아서 특수문자를 변환해 줍니다.
URI uri = new URI("http", "foo.com", "/hello world/", "");
URL url = uri.toURL();
MalformedURLException
URL 객체를 생성할 때 해당 URL 자원이 존재하지 않거나 올바르지 않은 프로토콜일 경우에 MalformedURLException 예외가 발생합니다. 이 예외는 catched exception이기 때문에 try-catch문으로 URL 생성코드를 감싸줘야 합니다.
URL myURL = new URL(". . .)
} catch (MalformedURLException e) {
. . .
// exception handler code here
. . .
}
Parsing a URL
아래의 코드를 보면 URL에 어떤 메소드들이 있는지 알 수 있습니다.
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://java.sun.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
결과는 다음과 같습니다.
authority = java.sun.com:80
host = java.sun.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
Reading Directly from a URL
다음과 같은 코드를 사용하여 URL에서 직접 콘텐츠를 읽어 들일 수 있습니다.
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/);
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Connecting to a URL
URL 객체를 생성한 다음 openConnection 메소드를 사용하여 URLConnection 객체를 생성할 수 있습니다. 다음은 Yahoo.com URL의 Connection 객체를 만드는 예제 코드입니다.
try {
URL yahoo = new URL("http://www.yahoo.com/);
URLConnection yahooConnection = yahoo.openConnection();
yahooConnection.connect();
} catch (MalformedURLException e) { // new URL() failed
. . .
} catch (IOException e) { // openConnection() failed
. . .
}
URLConnection.connect 메소드를 사용하여 Connection을 초기화 할 수 있는데 매번 명시적으로 호출하지 않아도 됩니다. getInputStream, getOutputStream 같은 메소드를 호출할 때 암묵적으로 호출하기 때문입니다.
Reading from and Writing to a URLConnection
URLConnection 클래스는 네트워크를 사용하여 URL과 의사소통을 하기 위한 다양한 메소드를 제공합니다. HTTP를 위한 기능들이 많이 있지만, 대부분의 다른 프로토콜을 위한 기능도 제공하고 있습니다.
Reading from a URLConnection
URL에서 직접 읽어오기와 비슷합니다.
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/);
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Writing to a URLConnection
URLConnection 객체를 사용하여 OutputStream 객체를 얻어서 ObjectOutputStream을 생성한 다음 URL로 원하는 데이터를 posting 한 뒤에 서버에서 처리한 결과를 URLConnection객체의 InputStream을 받아서 BufferedReader로 읽는 프로그램입니다.
import java.io.*;
import java.net.*;
public class Reverse {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse " +
"http://<location of your servlet/script>" +
" string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL("args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}