본문 바로가기
언어/네트워크 프로그래밍

[java 네트워크 프로그래밍] 6. URL 클래스

by hackeen 2015. 8. 10.
크리에이티브 커먼즈 라이선스
이 저작물은 크리에이티브 커먼즈 저작자표시-비영리-동일조건변경허락 2.0 대한민국 라이선스에 따라 이용할 수 있습니다.

1. .URL 클래스

 

1-1 URL 구조

 

http : //www.naver.com/

URL의 구조는 다음과 같이 프로토콜식별자(:)과 자원 이름(//www.naver.com/)으로 나누어진다.

자원의 이름은 다시 //www.myhom.net/index.html:8080 다음과 같은 형식으로 구성되는데 여기서

//www.myhom.net/은 호스트 이름, index.html은 파일 이름, :8080은 포트 번호로 나누어지게 된다.

1-2 자바의 URL 클래스

 

URL 클래스의 주요 생성자는 다음과 같다.

사진 1 URL 생성자

URL 클래스의 주요 메소드는 다음과 같다.

사진 2 URL 클래스의 주요 메소드

URL 클래스를 이용하여 연결된 상대편으로부터 데이터를 읽을 때는 그 전에 먼저 openStream() 메소드를 이용하여 입력 스트림을 연다. 그러고 나면 일반적인 입력 스트림에서 읽듯이 데이터를 읽어 온다.

 

1-3 URL 객체 생성

 

URL 객체를 생성하는 데에는 두 가지 방법이 있다. 절대경로를 이용하거나, 상대 경로를 이용하여 객체를 생성한다.

package PackageEx;

import java.net.MalformedURLException;
import java.net.URL;

public class WrapperEx {
    public static void main(String[] args) {
        URL opinion = null;
        URL homepage = null;
        try {
            homepage = new URL("http://news.hankooki.com"); //
절대 경로로 생성
            opinion = new URL(homepage, "opinion/deitorial.htm"); //
상대 경로로 생성
        } catch (MalformedURLException e) {
            System.out.println("
잘못된 URL입니다.");
        }
        System.out.println("Protocol = " + opinion.getProtocol()); // 프로토콜 출력
        System.out.println("host =" + opinion.getHost()); //
호스트 이름 출력
        System.out.println("port =" + opinion.getPath()); //
포트 번호 출력
        System.out.println("filename =" + opinion.getFile());

    }

}

 

2. URL 클래스를 이용한 읽기

 

package PackageEx;

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

public class WrapperEx {
    public static void main(String[] args) {
        try {
            URL aURL= new URL("http://www.nate.com");
            BufferedReader
in = new BufferedReader(new InputStreamReader(
aURL.openStream()));
            String
inputLine;
           
            while ((inputLine = in.readLine()) != null) //
행씩 읽기
                System.out.println(inputLine);
            in.close();
        } catch (IOException e) {
            System.out.println("URL
에서 데이터를 읽는 오류가 발생 했습니다.");
        }
    }
}

URLConnection 클래스를 이용한 데이터 읽기

package PackageEx;

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

public class WrapperEx {
    public static void main(String[] args) {
        try {
            URL aURL= new URL("http://www.nate.com");
            URLConnection
uc = aURL.openConnection();
           

            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
           

           
            String inputLine;
           
            while ((inputLine = in.readLine()) != null) //
행씩 읽기
                System.out.println(inputLine);
            in.close();
        } catch (IOException e) {
            System.out.println("URL
에서 데이터를 읽는 오류가 발생 했습니다.");
        }
    }
}

 

URL과 URLConnection의 가장 큰 차이점은 URL 객체와 달리 HTTP POST방식으로 서버에 데이터를 전송할 수 있다는 것이다.

 

3. URL 클래스를 이용한 쓰기

 

package PackageEx;

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

public class WrapperEx {
    public static void main(String[] args) {
        try {
            URL aURL= new URL("http://httpbin.org/post");
           

            URLConnection uc = aURL.openConnection();
            uc.setDoOutput(true);
            OutputStreamWriter
out = new OutputStreamWriter(
uc.getOutputStream());
            out.write("Firstname=Kitae&Lastname=Hwang");
            out.close();
            BufferedReader
in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
           

            String
inputLine;
            while((inputLine = in.readLine()) != null)
                System
.out.println(inputLine);
            in.close();
        } catch(IOException e){
            System
.out.println("URL
데이터를 입출력 중에 오류가 발생했습니다.");
        }
    }
}

댓글