블로그 이미지
GUCCI

카테고리

전체보기 (111)
여행 (1)
기기 (2)
쇼핑 (0)
게임 (0)
etc. (6)
취업이야기 (0)
업무일지 (5)
리눅스 (38)
웹프로그래밍 (2)
네트워크 (4)
JAVA (17)
Android (0)
IOS (2)
LUA (8)
C/C++ (1)
Objective C (2)
SERVER (2)
그누보드4 (1)
MSSQL (2)
Programming (1)
자바스크립트 (4)
HTML/CSS (1)
LGNAS (0)
Total
Today
Yesterday

'java.net'에 해당되는 글 1건

  1. 2011.03.03 java.net - Url 클래스 5

java.net - Url 클래스

JAVA / 2011. 3. 3. 15:50

import java.io.*;
import java.net.*;

public class UrlEx1 {
 public static void main(String[] args) throws Exception {
  String urlstr = null;
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("URL 페이지 입력 == >");
  urlstr = reader.readLine().trim();
  URL url = new URL(urlstr);
  System.out.println("프로토콜 : " + url.getProtocol());
  System.out.println("포트번호 : " + url.getPort());
  System.out.println("호스트 : " + url.getHost());
  System.out.println("URL 내용 : " + url.getContent());
  System.out.println("파일경로 : " + url.getFile());
  System.out.println("URL 전체 : " + url.toExternalForm());
 }
}


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

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

 

출처 : http://dumbung.com/main/bbs/board.php?bo_table=JAVA_LIBRARY&wr_id=27

'JAVA' 카테고리의 다른 글

이미지 태그 SRC 경로 추출  (3) 2011.03.16
파일명 추출  (2) 2011.03.16
Thread 클래스  (3) 2011.03.08
HttpURLConnection 이용시 헤더값 세팅 방법  (3) 2011.03.03
java.util 패키지  (3) 2011.03.03
Posted by GUCCI
, |

최근에 달린 댓글

글 보관함