Java - URL 클래스,URLEncoder,URLDecoder

2020. 7. 29. 22:29Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
 
public class Ex {
 
    public static void main(String[] args) {
        
        /*
         * URL 클래스
         * -URL(Uniform Resource Locator) 이란?
         * 웹 상의 자원들의 위치를 가르키는 포인터(주소)
         * -URL 형식
         * ex) http://www.itwillbs.co.kr:80/index.jsp
         * 1)http- 프로토콜(Protocol)
         * 2)www.itwillbs.co.kr-호스트명
         * 3)80 -포트번호
         * 4)index.jsp-경로(Path) 및 파일(File)
         */
        
//        BufferedReader buffer=null;
        
//        try {
//            //특정 주소를 갖는 URL 객체 생성
//            URL url=new URL("http://www.naver.com");
//            
//            //URL 객체로부터 입력스트림(InputStream) 연결
////            InputStream is=url.openStream();
//            
//            //byte 단위로 처리되는 입력스트림을 촘ㄱ 단위로 변환하기 위해
//            //InputStreamReader 객체 생성
////            InputStreamReader reader=new InputStreamReader(is);
//            
//            //위의 두 문장을 한 문장으로 결합
////            InputStreamReader reader=new InputStreamReader(url.openStream());
//            
//            //BufferedReader 객체를 사용하여 char 단위-> String 단위로 변환하여 처리
//            buffer=new BufferedReader(new InputStreamReader(url.openStream()));
//            
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }finally {
//            try {
//                buffer.close();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
        
        URL url=null;
        try {
             url=new URL("http://www.naver.com");
             System.out.println("프로토콜 : "+url.getProtocol());
             System.out.println("호스트명 : "+url.getHost());
             System.out.println("포트번호 : "+url.getPort());
             System.out.println("파일명 : "+url.getFile());
             
        }catch(MalformedURLException e) {
            e.printStackTrace();
        }
        //----------------------------------------------------
        
        try {
            //지정된 도메인(URL)을 사용하여 연결 수행 후 URLConnection 객체 가져오기
            URLConnection con=url.openConnection();
            con.connect();//URL 에 접속(연결) 수행
            System.out.println("문서 타입 : "+con.getContentType());
            System.out.println("문서 크기 : "+con.getContentLength()+"바이트");
            System.out.println("문서 최종 수정일자 : "+new Date(con.getLastModified()));
            
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //-------------------------------------------------------
        
        try {
             url=new URL("http://www.naver.com");
             System.out.println("프로토콜 : "+url.getProtocol());
             System.out.println("호스트명 : "+url.getHost());
             System.out.println("포트번호 : "+url.getPort());
             System.out.println("파일명 : "+url.getFile());
             
        }catch(MalformedURLException e) {
            e.printStackTrace();
        }
        //---------------------------------------------------------
        
        try(BufferedReader buffer=new BufferedReader(new InputStreamReader(url.openStream()))){
            //버퍼로부터 입력되는 입력스트림을 한 문장 읽어서 변수에 저장
            String str=buffer.readLine();
            
            //읽어온 문장이 null 이 아닐 동안 반복해서 읽어오기
            //->읽어온 문장 출력 후 새로운 문장 읽어오기
            
            while(str!=null) {
                System.out.println(str);
                str=buffer.readLine();
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
 
}
 
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
 
import javax.activation.URLDataSource;
 
public class Ex2 {
 
    public static void main(String[] args) {
        
        /*
         * URLEncoder, URLDecoder 클래스
         * -문자열을 MIME 형식으로 변환하기 위한 클래스
         * 주로 한글로 표시되는 쿼리 문자열 등이 웹 서버에 전송될 때의 형태
         * 특정 규칙에 따라 변환 되어짐
         * 1) 아스키 코드(영문 대문자, 소문자, 숫자, 특수문자 등)는 그대로 사용
         * 2) 공백은 + 기호로 변환
         * 3) 기타 문자(한글,한자 등)는 %XX형태의 16진수로 변환됨.
         * 
         * ex) 네이버 검색창에 ITWILL 부산교육센터 검색했을 때
         * https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=
         * ITWILL+%EB%B6%80%EC%82%B0%EA%B5%90%EC%9C%A1%EC%84%BC%ED%84%B0
         * -한글 부분이 다른 형태의 문자로 표시됨
         */
        
        try {
            String originalStr="[Java Programming : 아이티윌]";
            System.out.println("원본 문자열 : "+originalStr);
            //URLEncoder 클래스를 사용하여 원본 문자열을 MIME 형식으로 변환 (인코딩)
            String encodeStr=URLEncoder.encode(originalStr,"UTF-8");
            System.out.println("MIME 형식 변환 후 : "+ encodeStr);
            
            //URLDecoder 클래스를 사용하여 MIME 형식 문자열을 원래 문자열로 변환(디코딩)
            String decodeStr=URLDecoder.decode(encodeStr,"UTF-8");
            System.out.println("원본으로 복원 후 : "+decodeStr);
        } catch (UnsupportedEncodingException e) {
            //지정된 인코딩 타입(UTF-8 등)이 지원되지 않을 경우 발생하는 예외
            e.printStackTrace();
        }
        
    }
 
}
 
 
cs

 

Encoder와 Decoder를 배워보았다. 흔히 보이는 주소창이 어떻게 주소가 넘어가고 받아들여지는지 알아보았는데

흔히들 생각하는 인코딩 디코딩은 압축과 압축 풀기의 개념이 아니고 컴퓨터가 받아들일 수 있게 분해하는 과정이라고 생각하면 될 것 같았다. 컴퓨터를 다루다 보면 네트워크 연결의 문제가 생길 수도 있고 알아두면 나쁠 게 없으니 알아둬야겠다.