WebApp Java에서 URL 다루기

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

참조 : 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();
    }
}

 

 

 

번호 제목 글쓴이 날짜 조회 수
347 java.util.Optional 에서의 map() 함수의 이해 황제낙엽 2026.06.24 666
346 linux(ubuntu) 의 jdk 21 이 설정된 환경에서 jdk 17 로 다운그레이드 절차 황제낙엽 2025.09.22 1532
345 [ChatGPT] javax.* 패키지와 jakarta.* 패키지의 혼합 사용 방안 황제낙엽 2025.04.15 2459
344 [ChatGPT] *.servlet.http.HttpServlet 클래스를 사용할 수 있는 주요 WAS 목록 황제낙엽 2025.04.14 2038
343 [ChatGPT] JDBC API에서 java.sql과 javax.sql 패키지의 차이점 황제낙엽 2025.01.31 2218
342 jakarta.servlet 패키지를 이용한 File Upload 구현 (2024.03.03, Servlet 5.0) 황제낙엽 2025.01.02 2310
341 [ChatGPT] Java EE가 Jakarta EE로 전환 황제낙엽 2025.01.01 2525
340 [ChatGPT] File.delete() 함수로 파일 삭제가 되지 않는 경우 황제낙엽 2024.12.10 2809
339 [ChatGPT] <jsp:include>에서 flush="true"를 설정시의 몇 가지 문제점 과 대안 황제낙엽 2024.07.19 2493
338 [Copilot] JSP, Servlet, web.xml, mysql 한글 설정 황제낙엽 2024.07.12 2555
337 Base64 클래스의 encode, decode 에서 URL-safe 황제낙엽 2024.07.10 2624
336 [Copilot] JSP 에서 다른 페이지를 현재 페이지에 포함시키는 문법 (include) 황제낙엽 2024.06.26 2570
335 Exception 출력에 대한 고찰 황제낙엽 2024.06.10 2198
334 google-auth-library-oauth2-http 라이브러리 다운로드 황제낙엽 2023.11.19 4025
333 firebase-admin-java 라이브러리 다운로드 (firebase admin sdk library) 황제낙엽 2023.11.19 2805
332 Enum 활용 (개인블로그, Effective Java) file 황제낙엽 2023.11.02 2759
331 Enum 활용 (우아한기술블로그) file 황제낙엽 2023.11.02 2790
330 servlet name 에 camel case 를 사용해서는 안되는 이유 황제낙엽 2023.10.24 2508
329 org.apache.commons.fileupload.servlet.ServletFileUpload 이용 예시 황제낙엽 2023.08.25 3336
328 ServletFileUpload.parseRequest() 실행 결과 리스트가 비어있는 오류 황제낙엽 2023.08.25 2935