Presentation is loading. Please wait.

Presentation is loading. Please wait.

10장 URLConnection 클래스 홍창범 시스템 소프트웨어 연구실 System Software Lab.

Similar presentations


Presentation on theme: "10장 URLConnection 클래스 홍창범 시스템 소프트웨어 연구실 System Software Lab."— Presentation transcript:

1 10장 URLConnection 클래스 홍창범 시스템 소프트웨어 연구실 System Software Lab.

2 URLConnection 클래스 - URLConnection열기
System Software Lab. 목 차 URLConnection 클래스 - URLConnection열기 - 서버로부터 데이터를 가져오는 메소드 - 헤더의 구문 분석 - 필드와 관련 메소드 유용한 프로그램 - HTTP 연결을 통한 이진 데이터 다운로드하기 - 폼 데이터를 POST 방식으로 전송하기

3 URLConnection 클래스 URLConnection 클래스 - URL보다 서버와의 대화에 대해서 더 많이 제어.
System Software Lab. URLConnection 클래스 URLConnection 클래스 URL에 의하여 지정되는 자원에 대한 활성화된 연결을 나타내는 추상클래스 - URL보다 서버와의 대화에 대해서 더 많이 제어. - URLStreamHandler 클래스를 포함하는 프로토콜 핸들러 메커니즘의 일부

4 System Software Lab. URLConnection 열기 Public URLConnection openConnection() throws IOException 로컬 호스트와 원격 호스트간 데이터가 이동할수있는 실질적 연결 생성 >> 예제 URL u; URLConnection uc; try { URL u = new URL(" URLConnection uc = u.openConnection(); }

5 서버로부터 데이터를 가져오는 메소드들 Public abstract void connect() throws IOException
System Software Lab. 서버로부터 데이터를 가져오는 메소드들 Public abstract void connect() throws IOException 서버에 대해 연결을 해주는 추상 메소드 서버의 이름은 URLConnection의 생성자에게 인자로 넘겨진 후 이 클래스의 필드에 저장되어 있는 URL로부터 추출

6 서버로부터 데이터를 가져오는 메소드들 (계속)
System Software Lab. 서버로부터 데이터를 가져오는 메소드들 (계속) Public Object getContent() throws IOException URL이 가리키는 데이터를 가져옴. 특정한 객체의 유형으로 변환(ASCII,HTML-inputStream/gif/jpg-imageProduce) MIME헤더의 content-type을 이용. 현재 이해되는 유형 text/html, image/gif, image/jpeg 가 있다.

7 서버로부터 데이터를 가져오는 메소드들(계속)
System Software Lab. 서버로부터 데이터를 가져오는 메소드들(계속) FileInputStream LineNumberInputStream PipedInputStream DataInputStream FilterInputStream BufferInnputStream InputStream ByteArrayInputStream PushbackInputStream SequenceInputStream StringBufferInputStream ObjectInputStream FileOutputStream PipeOutputStream DataOutputStream OutputStream FilterOutputStream BufferedOutputStream ByteArrayOutputStream PushbackOutputStream ObjectOutputStream [Java.io 패키지의 입출력 스트림클래스들의 계층구조]

8 서버로부터 데이터를 가져오는 메소드들 (계속)
Public InputStream getInputStream() - URLConnection 객체를 생성하고 그 객체에 대한 입력 스트림을 구한다. >>예제 uc = u.openConnection(); DataInputStream theHTML = new DataInputStream(uc.getInputStream()); Try{ while ((thisLine = theHTML.readLine()) != null) { System.out.println(thisLine); } URLConnection객체생성 생성된 객체에 대한 입력스트림을 구한다. >> 실행결과 %java viewsource2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=euc-kr"> <title>한남대학교</title> ~ </html> System Software Lab.

9 서버로부터 데이터를 가져오는 메소드들 (계속)
Public OutputStream getOutputStream() - URLConnection 객체를 생성하고 그 객체에 대한 출력스트림(Output Stream:서버에 전 송할 데이터를 쓸 수 있는)을 구한다. - URLConnection은 기본적으로 출력을 지원하지 않느다. - 출력스트림을 요청하기 전에 setDoOutput()을 호출해야 한다. >>예제 try { URL u = new URL( URLConnection uc = u.openConnection(); uc.setDoOutput(true); DataOutputStream dos = new DataOutputStream(uc.getOutputStream()); dos.writeBytes(“Here is some data”); dos.close(); } catch ( Exception e) { System.out.println(e); 생성된 객체에 대한 출력스트림을 구한다. System Software Lab.

10 헤더의 구문 분석 [Server] [Client] [Server 와 Client와의 통신]
System Software Lab. 헤더의 구문 분석 [Server] [Client] 수신한 Request 메세지 분석 Web 페이지를 요구하는 HTTP Request 메세지 요구된 Web 페이지를 포함하는 HTTP Response 메시지 생성 Request-Line General-Header Request-Header Entity-Header CRLF Entity-Body Status-Line General-Header Response-Header Entity-Header CRLF Entity-Body 전달된 페이지의 디스플레이 [Server 와 Client와의 통신] System Software Lab.

11 헤더의 구문 분석 (계속) System Software Lab.
일반 HTTP 헤더(General HTTP Header) Pragma 응답혹은 요청 연결선상의 수신인에게 적용되는 일종의 명령포함(no-cache) Date 응답 혹은 요청이 만들어진 날짜 시간 엔티티 HTTP 헤더(Entity HTTP Header) Content-Encoding 인코딩 방법 Content-Length 크기 Content-Type MIME타입 요청 HTTP 헤더(Request HTTP Header) From 전자우편주소 Accept 브라우저가 처리할수 있는 MIME타입목록 Accept-Encoding 인코팅방법 Accept-Language 언어 User_agent S/W이름 버전 Referer 요청 직전 보고 있던 웹페이지 Authorization 인증정보 If-Modified-Since 지정된 시각 이후 요청된 자원이 변경된 적이 없으면 에러 응답 HTTP 헤더(Response HTTP Header) Location URL이 가리켰던 위치 Server 서버정보 WWW-Authenticate 인증 방법

12 헤더의 구문 분석 (계속) [Response Header 의 예] System Software Lab.
public String getContentType() Server Microsoft-IIS/5.0 syssw Made By Hong_chang_bum Cache-Control max-age=602938 Expires Thu, 25 May :00:00 GMT Connection keep-alive Content-Location Date Thu, 18 May :31:01 GMT Content-Type text/html Accept-Ranges bytes Last-Modified Wed, 17 May :22:46 GMT ETag " db7bfbf1:b47" Content-Length 213 public String getContentLength() public String getContentEncoding() public long getDate() public long getExpiration() public long LastModified()

13 헤더의 구문 분석 (계속) public String getContentType()
System Software Lab. 헤더의 구문 분석 (계속) 1 public String getContentType() 데이터의 컨텐트 유형 반환 컨텐트 유형의 정보가 없을경우 null 반환 예) text/plain, image/gif, image/jpega (67Page 참고) 2 public String getContentLength() 컨텐트가 몇 바이트로 이루져 있는지를 알려준다. 헤더에 정보가 없을경우 –1을 반환 3 public String getContentEncoding() 컨텐트가 코드화된 방법을 반환 컨텐트가 코드화되지 않은 상태로 전송 되었다면 null 반환 코드화 방법 Base-64, quoted-printable

14 헤더의 구문 분석 (계속) public long getDate() public long getExpiration()
System Software Lab. 헤더의 구문 분석 (계속) 4 public long getDate() 문서의 전송 날짜를 반환 public long getExpiration() 5 문서만기일을 반환 6 public long getLastModified() 문서의 최종 수정된 날짜를 반환

15 헤더의 구문 분석 (계속) >> 예제 for (int i=0; i < args.length; i++) {
System Software Lab. 헤더의 구문 분석 (계속) >> 예제 for (int i=0; i < args.length; i++) { try { URL u = new URL(args[0]); URLConnection uc = u.openConnection(); System.out.println("Content-type: " + uc.getContentType()); System.out.println("Content-encoding: " + uc.getContentEncoding()); System.out.println("Date: " + new java.util.Date(uc.getDate())); System.out.println("Last modified: " + new java.util.Date(uc.getLastModified())); System.out.println("Expiration date: " + new java.util.Date(uc.getExpiration())); System.out.println("Content-length: " + uc.getContentLength()); } // end try

16 헤더의 구문 분석 (계속) >> 실행결과
System Software Lab. 헤더의 구문 분석 (계속) >> 실행결과 %java getMIMEHeader Content-type: text/html Content-encoding: null Date: Sat May 20 18:57:31 GMT+09: Last modified: Thu Jan 01 09:00:00 GMT+09: Expiration date: Thu Jan 01 09:00:00 GMT+09: Content-length: -1

17 임의의 MIME 헤더 필드 값을 가져오기 인자로 넘겨진 name이라는 헤더 필드값을 반환
System Software Lab. 임의의 MIME 헤더 필드 값을 가져오기 public String getHeaderField(String name) 인자로 넘겨진 name이라는 헤더 필드값을 반환 uc.getHeaderField(“content-type”); uc.getHeadField(“content-encoding”); uc.getHeadField(“date”); uc.getHeadField(“expires”);

18 임의의 MIME 헤더 필드 값을 가져오기 public String getHeaderFieldKey(int n)
System Software Lab. 임의의 MIME 헤더 필드 값을 가져오기 public String getHeaderFieldKey(int n) n번째 헤더의 필드키를 반환 String header5 = uc.getHeaderFieldKey(5);

19 System Software Lab. 임의의 MIME 헤더 필드 값을 가져오기 public long getHeaderFieldDate(String name, long default) name이 가리키는 헤더 필드값을 가져와서 문자열로된 값을 long으로 변환 uc.getHeaderFieldData(“expires” , -1); uc.getHeaderFieldData(“last-modification”, -1); uc.getHeaderFieldData(“date”, -1);

20 System Software Lab. 임의의 MIME 헤더 필드 값을 가져오기 public String getHeaderFieldInt(String name, int default) name의 헤더 필드의 값을 가져와 int로 변환 후 반환 int cl = uc.getHeaderFieldInt(“content-length”, -1);

21 임의의 MIME 헤더 필드 값을 가져오기 (계속)
System Software Lab. 임의의 MIME 헤더 필드 값을 가져오기 (계속) >>예제 for (int i=0; i < args.length; i++) { try { u = new URL(args[i]); uc = u.openConnection(); for (int j = 1; ; j++) { header = uc.getHeaderField(j); if (header == null) break; System.out.println(uc.getHeaderFieldKey(j) + " " + header); } // end for } // end try >>결과 %java printMIMEHeader Date Thu, 01 Jun :25:58 GMT Server Apache/1.3.9 (Unix) PHP/3.0.12 Connection close Content-Type text/html

22 MIME 유형 알아내기 URL에서 파일이름 부분의 확장자를 기초로 하여 컨텐트 유형을 추측해낸다.
System Software Lab. MIME 유형 알아내기 protected static String guessContentTypeFromName(String name) URL에서 파일이름 부분의 확장자를 기초로 하여 컨텐트 유형을 추측해낸다. 확장자는 대소문자를 구별한다. 예) .dvi application/x-dvi .zip application/zip .tar application/x-tar .gif image/gif

23 MIME 유형 알아내기 (계속) Inputstream의 최초 6바이트를 읽어 컨텐트 유형을 추측한다. 예)
System Software Lab. MIME 유형 알아내기 (계속) static protected String guessContentTypeFromStream(InputStream is) Inputstream의 최초 6바이트를 읽어 컨텐트 유형을 추측한다. 예) GIF8 image/gif #def image/x-bitmap <! text/html <html> text/html

24 System Software Lab. RequestProperty 메소드들 URLConnection에서는 아무런 일도 하지 않고, 해시테이블 조회 클래스 구현시 치환하게 된다. public String getRequestProperty(String property_name) 치환하게되면, 주어진 속성의 값을 문자열로 반환 public static void setDefaultRequestProperty(String property_name, String property_value) 치환하게되면, 주어진 속성에 대해 기본값을 설정 public static void setRequestProperty(String property_name, String property_value) 치환하게되면, 주어진 속성의 값을 설정 public static void getDefaultRequestProperty(String property_name) 치환하게되면, 할당된 초기값을 문자열로서 주어진 속성으로 반환되어야 한다.

25 필드와 관련 메소드들 try { u = new URL("http://www.ora.com/");
System Software Lab. 필드와 관련 메소드들 protected URL url public URL getURL() URLConnection이 연결하고자 하는 URL을 가리킨다. try { u = new URL(" uc = u.openConnection(); System.out.println(uc.getURL()); } catch (IOException e) { System.err.println(e); >>결과 %java printURLConnection

26 필드와 관련 메소드들 (계속) protected boolean connected
System Software Lab. 필드와 관련 메소드들 (계속) protected boolean connected 연결이 열려 있으면 true, 닫혀 있으면 false. URLConnection은 생성되어도 연결되어 있지 않은 상태이므로 기본적으로 false이다.

27 필드와 관련 메소드들 (계속) protected boolean allowUserInteraction
System Software Lab. 필드와 관련 메소드들 (계속) protected boolean allowUserInteraction public void setAllowUserInteraction(boolean allowuserinteraction) public boolen getAllowUserInteraction() 사용자와의 대화가 가능한지를 지정한다. try { u = new URL(" handler = new myHttpHandler(); uc = handler.openConnection(u); if (!uc.getAllowUserInteraction()) { uc.setAllowUserInteraction(true); } catch (MalformedURLException e) { System.err.println(e);

28 필드와 관련 메소드들 (계속) private static boolean defaultAllowUserInteraction
System Software Lab. 필드와 관련 메소드들 (계속) private static boolean defaultAllowUserInteraction public static void setDefaultAllowUserInteraction (boolean defaultAllowUserInteraction) public static boolean getDefaultAllowUserInteraction() 기본적으로 사용자와의 대화가 가능한지를 지정한다. public static void main(String[ ] args) { if (!URLConnection.getDefaultAllowUserInteraction()) { URLConnection.getDefaultAllowUserInteraction(true) ; }

29 필드와 관련 메소드들 (계속) protected boolean doInput
System Software Lab. 필드와 관련 메소드들 (계속) protected boolean doInput public void setDoInput(boolean doinput) public boolean getDoInput() try { u = new URL(" uc = u.openConnection(); if (!uc.getDoInput()) { uc.setDoInput(true); } catch (IOException e) { System.err.println(e); 클라이언트 프로그램으로의 데이터 입력이 가능한지 체크후 능하도록 설정

30 필드와 관련 메소드들 (계속) protected boolean doOutput
System Software Lab. 필드와 관련 메소드들 (계속) protected boolean doOutput public void setDoInput(boolean dooutput) public boolean getDoOutput() try { u = new URL(" uc = u.openConnection(); if (!uc.getDoOutput()) { uc.setDoOutput(true); } catch (IOException e) { System.err.println(e); 서버로 부터 출력작업이 가능한지 체크후 가능하도록 설정

31 필드와 관련 메소드들 (계속) protected long IfModifiedSince
System Software Lab. 필드와 관련 메소드들 (계속) protected long IfModifiedSince public void setIfModifiedSince(long ifmodifiedsince) public long getIfModifiedSince() try { u = new URL(" uc = u.openConnection(); System.out.println("Will retrieve file if it's been modified since " + new Date(uc.getIfModifiedSince()).toLocaleString()); uc.setIfModifiedSince(Date.UTC(today.getYear(), today.getMonth(), today.getDate() - 1, today.getHours(), today.getMinutes(), today.getSeconds())); } >>결과 %java last24 Will retrieve file if it's been modified since 오전 9:00:00 Will retrieve file if it's been modified since 오전 10:53:13 %date

32 필드와 관련 메소드들 (계속) pritected static boolean userCaches
System Software Lab. 필드와 관련 메소드들 (계속) pritected static boolean userCaches public static void setUseCaches(boolean usecaches) public static boolean getUseCaches() 로컬 캐시의 사용 여부 결정 try { u = new URL(" uc = u.openConnection(); if (uc.getUseCaches()) { uc.setUseCaches(false); } 캐시기능의 정지

33 필드와 관련 메소드들 (계속) pritected static boolean defalutUserCaches
System Software Lab. 필드와 관련 메소드들 (계속) pritected static boolean defalutUserCaches public static void setDefaultUseCaches(boolean defaultusecaches) public static boolean getDefaultUseCaches() 기본적으로 캐시 기능의 사용여부 선택 try { URL u = new URL(" URLConnection uc = u.openConnection(); if (uc.getDefaultUseCaches()) { uc.setDefaultUseCaches(false); } catch (IOException e) { System.err.println(e); 기본적으로 캐시기능 정지

34 필드와 관련 메소드들 (계속) static ContentHandlerFactory factory
System Software Lab. 필드와 관련 메소드들 (계속) static ContentHandlerFactory factory public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac) : 특정한 MIME 유형에 적합한 컨텐트 핸들러의 인스턴스 생성 text/html , image/gif파일등을 처리할 수 있는 컨텐트 핸들러를 찾을 수 있도록 알려준다.

35 유용한 프로그램들 (HTTP 연결을 통해 이진 데이터를 다운로드하기)
System Software Lab. 유용한 프로그램들 (HTTP 연결을 통해 이진 데이터를 다운로드하기) public static void saveBinaryFile(URL u) { int bfr = 128; try { URLConnection uc = u.openConnection(); String ct = uc.getContentType(); int cl = uc.getContentLength(); if (ct.startsWith("text/") || cl == -1 ) { System.err.println("This is not a binary file."); return; } InputStream theImage = uc.getInputStream(); byte[] b = new byte[cl]; int bytesread = 0; int offset = 0; while (bytesread >= 0) { bytesread = theImage.read(b, offset, bfr); if (bytesread == -1) break; offset += bytesread; if (offset != cl) { System.err.println("Error: Only read " + offset + " bytes"); System.err.println("Expected " + cl + " bytes"); String theFile = u.getFile(); theFile = theFile.substring(theFile.lastIndexOf('/') + 1); FileOutputStream fout = new FileOutputStream(theFile); fout.write(b); } // end try catch (Exception e) { System.err.println(e); 연결확보 입력스트림을 구한다. 배열을 읽어들인다. 출력스트림을 구한다. 파일로 쓰여진다.

36 유용한 프로그램들 (폼 데이터를 POST 방식으로 전송하기)
System Software Lab. 유용한 프로그램들 (폼 데이터를 POST 방식으로 전송하기) void submitData() { String query = "name=" + URLEncoder.encode("Elliotte Rusty Harold"); query += "&"; query += " =" + int cl = query.length(); try { URLConnection uc = u.openConnection(); uc.setDoOutput(true); uc.setDoInput(true); uc.setAllowUserInteraction(false); DataOutputStream dos = new DataOutputStream(uc.getOutputStream()); dos.writeBytes(query); dos.close(); DataInputStream dis = new DataInputStream(uc.getInputStream()); String nextline; while((nextline = dis.readLine()) != null) { System.out.println(nextline); 연결확보 생성된 객체에 대한 출력스트림을 구한다. 데이터를 전송한다. 생성된 객체에 대한 입력스트림을 구한다. 서버로 부터 응답을 읽는다. 출력된다.


Download ppt "10장 URLConnection 클래스 홍창범 시스템 소프트웨어 연구실 System Software Lab."

Similar presentations


Ads by Google