WebApp Java에서 URL 다루기

황제낙엽 2012.06.24 15:03 조회 수 : 396

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)를 의미합니다.

 

378.gif

 


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 생성코드를 감싸줘야 합니다.

 

 

 

try {
    URL myURL = new URL(". . .)
} catch (MalformedURLException e) {
    . . .
    // exception handler code here
    . . .
}


Parsing a URL

아래의 코드를 보면 URL에 어떤 메소드들이 있는지 알 수 있습니다.

 

 

import java.net.*;
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());
    }
}


결과는 다음과 같습니다.

 

 

protocol = http
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.net.*;
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.net.*;
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();
    }
}

 

 

 

번호 제목 글쓴이 날짜 조회 수
223 String to InputSource 황제낙엽 2012.12.03 601
222 Class.getResource() vs. ClassLoader.getResource()/getResources() 황제낙엽 2012.06.24 466
221 Jar파일에 포함된 리소스 접근하는 방법(How to read a resource from a JAR file ) file 황제낙엽 2012.06.24 475
» Java에서 URL 다루기 file 황제낙엽 2012.06.24 396
219 HttpServletResponse.setContentType(java.lang.String type) 과 MIME 타입 황제낙엽 2012.04.20 509
218 code, codebase 속성과 applet object 동적 생성 file 황제낙엽 2012.04.17 451
217 한글 파일명 깨짐으로 살펴본 다국어 처리 문제 (UTF-8) 황제낙엽 2012.03.22 10403
216 BufferedReader.readLine() hangs 황제낙엽 2012.02.23 809
215 OS 쉘 명령어(shell script) 실행하기 [ProcessBuilder, Runtime.getRuntime().exec()] 황제낙엽 2012.02.22 923
214 PreProcess 실행 (전처리기 만들기) file 황제낙엽 2012.01.04 478
213 javax.script와 타입변환 황제낙엽 2012.01.03 430
212 Scripting within Java 황제낙엽 2012.01.03 393
211 Hex string <-> String object 황제낙엽 2011.11.29 611
210 An alternative to the deep copy technique file 황제낙엽 2011.07.27 570
209 <jsp:include>, include지시자 file 황제낙엽 2011.07.24 438
208 <jsp:include> 액션태그 황제낙엽 2011.07.24 403
207 volatile 에 대한 단상(斷想) 황제낙엽 2011.06.22 425
206 Object element 의 onerror 이벤트 황제낙엽 2011.04.21 295
205 Java 2D Graphics - Reference link 황제낙엽 2011.04.11 459
204 deployJava.js를 이용한 JRE 자동설치 및 Applet 디플로이 file 황제낙엽 2011.04.04 943