System Software Lab.
description
Transcript of System Software Lab.
1System Software Lab.
10 장 URLConnection 클래스
홍창범
시스템 소프트웨어 연구실
2System Software Lab.
목 차
URLConnection 클래스
- URLConnection 열기
- 서버로부터 데이터를 가져오는 메소드
- 헤더의 구문 분석
- 필드와 관련 메소드
유용한 프로그램
- HTTP 연결을 통한 이진 데이터 다운로드하기
- 폼 데이터를 POST 방식으로 전송하기
3System Software Lab.
URLConnection 클래스
URLConnection 클래스 URL 에 의하여 지정되는 자원에 대한 활성화된 연결을 나타내는 추상클래스
- URL 보다 서버와의 대화에 대해서 더 많이 제어 .
- URLStreamHandler 클래스를 포함하는 프로토콜 핸들러 메커니즘의 일부
4System Software Lab.
URLConnection 열기
Public URLConnection openConnection() throws IOException
로컬 호스트와 원격 호스트간 데이터가 이동할수있는 실질적 연결 생성
>> 예제
URL u;
URLConnection uc;
try {
URL u = new URL("http://www.ora.com");
try {
URLConnection uc = u.openConnection();
}
5System Software Lab.
서버로부터 데이터를 가져오는 메소드들
Public abstract void connect() throws IOException
서버에 대해 연결을 해주는 추상 메소드
서버의 이름은 URLConnection 의 생성자에게 인자로 넘겨진 후 이 클래스의 필드에 저장되어 있는 URL 로부터 추출
6System Software Lab.
서버로부터 데이터를 가져오는 메소드들 ( 계속 )
Public Object getContent() throws IOException
URL 이 가리키는 데이터를 가져옴 .
특정한 객체의 유형으로 변환 (ASCII,HTML-inputStream/gif/jpg-imageProduce)
MIME 헤더의 content-type 을 이용 .
현재 이해되는 유형 text/html, image/gif, image/jpeg 가 있다 .
7System Software Lab.
서버로부터 데이터를 가져오는 메소드들 ( 계속 )
FileInputStream
PipedInputStream
FilterInputStream
ByteArrayInputStream
SequenceInputStream
StringBufferInputStream
ObjectInputStream
InputStream
LineNumberInputStream
DataInputStream
BufferInnputStream
PushbackInputStream
OutputStream
FileOutputStream
PipeOutputStream
FilterOutputStream
ByteArrayOutputStream
ObjectOutputStream
DataOutputStream
BufferedOutputStream
PushbackOutputStream
[Java.io 패키지의 입출력 스트림클래스들의 계층구조 ]
8System Software Lab.
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 http://www.hannam.ac.kr
<!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>
9System Software Lab.
Public OutputStream getOutputStream()
- URLConnection 객체를 생성하고 그 객체에 대한 출력스트림 (Output Stream: 서버에 전
송할 데이터를 쓸 수 있는 ) 을 구한다 .- URLConnection 은 기본적으로 출력을 지원하지 않느다 .
- 출력스트림을 요청하기 전에 setDoOutput() 을 호출해야 한다 .
서버로부터 데이터를 가져오는 메소드들 ( 계속 )
>> 예제
try {
URL u = new URL( http://www.somehost.com/cgi-bin/acgi);
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);
}
생성된 객체에 대한
출력스트림을 구한다 .
10System Software Lab.System Software Lab.
헤더의 구문 분석
[Server] [Client]
Web 페이지를 요구하는 HTTP Request 메세지
수신한 Request
메세지 분석
요구된 Web 페이지를 포함하는 HTTP Response 메시지 생성
전달된 페이지의
디스플레이
Request-Line
General-Header
Request-Header
Entity-Header
CRLF
Entity-BodyStatus-Line
General-Header
Response-Header
Entity-Header
CRLF
Entity-Body
[Server 와 Client 와의 통신 ]
11System 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 인증 방법
헤더의 구문 분석 ( 계속 )
12System Software Lab.
헤더의 구문 분석 ( 계속 )
[Response Header 의 예 ]
Server Microsoft-IIS/5.0
syssw Made By Hong_chang_bum
Cache-Control max-age=602938
Expires Thu, 25 May 2000 15:00:00 GMT
Connection keep-alive
Content-Location http://syssw/index.htm
Date Thu, 18 May 2000 15:31:01 GMT
Content-Type text/html
Accept-Ranges bytes
Last-Modified Wed, 17 May 2000 04:22:46 GMT
ETag "1685808db7bfbf1:b47"
Content-Length 213
public String getContentType()
public String getContentLength()
public String getContentEncoding()
public long getDate()
public long getExpiration()
public long LastModified()
13System Software Lab.
헤더의 구문 분석 ( 계속 )
1
2
3
public String getContentType()
데이터의 컨텐트 유형 반환
컨텐트 유형의 정보가 없을경우 null 반환
예 ) text/plain, image/gif, image/jpega (67Page 참고 )
public String getContentLength()
컨텐트가 몇 바이트로 이루져 있는지를 알려준다 .
헤더에 정보가 없을경우 – 1 을 반환
public String getContentEncoding()
컨텐트가 코드화된 방법을 반환
컨텐트가 코드화되지 않은 상태로 전송 되었다면 null 반환
코드화 방법 Base-64, quoted-printable
14System Software Lab.
헤더의 구문 분석 ( 계속 )
4
5
6
public long getDate()
문서의 전송 날짜를 반환
public long getExpiration()
문서만기일을 반환
public long getLastModified()
문서의 최종 수정된 날짜를 반환
15System 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
16System Software Lab.
헤더의 구문 분석 ( 계속 )
>> 실행결과
%java getMIMEHeader http://ce.hannam.ac.kr
Content-type: text/html
Content-encoding: null
Date: Sat May 20 18:57:31 GMT+09:00 2000
Last modified: Thu Jan 01 09:00:00 GMT+09:00 1970
Expiration date: Thu Jan 01 09:00:00 GMT+09:00 1970
Content-length: -1
17System Software Lab.
임의의 MIME 헤더 필드 값을 가져오기
public String getHeaderField(String name)
인자로 넘겨진 name 이라는 헤더 필드값을 반환
uc.getHeaderField(“content-type”);
uc.getHeadField(“content-encoding”);
uc.getHeadField(“date”);
uc.getHeadField(“expires”);
18System Software Lab.
임의의 MIME 헤더 필드 값을 가져오기
public String getHeaderFieldKey(int n)
n번째 헤더의 필드키를 반환
String header5 = uc.getHeaderFieldKey(5);
19System 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);
20System Software Lab.
임의의 MIME 헤더 필드 값을 가져오기
public String getHeaderFieldInt(String name, int default)
name 의 헤더 필드의 값을 가져와 int 로 변환 후 반환
int cl = uc.getHeaderFieldInt(“content-length”, -1);
21System 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 http://ce.hannam.ac.kr
Date Thu, 01 Jun 2000 02:25:58 GMT
Server Apache/1.3.9 (Unix) PHP/3.0.12
Connection close
Content-Type text/html
22System Software Lab.
MIME 유형 알아내기
protected static String guessContentTypeFromName(String name)
URL 에서 파일이름 부분의 확장자를 기초로 하여 컨텐트 유형을 추측해낸다 .
확장자는 대소문자를 구별한다 .
예 )
.dvi application/x-dvi
.zip application/zip
.tar application/x-tar
.gif image/gif
23System Software Lab.
MIME 유형 알아내기 ( 계속 )
static protected String guessContentTypeFromStream(InputStream is)
Inputstream 의 최초 6바이트를 읽어 컨텐트 유형을 추측한다 .
예 )
GIF8 image/gif
#def image/x-bitmap
<! text/html
<html> text/html
24System 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)
치환하게되면 , 할당된 초기값을 문자열로서 주어진 속성으로 반환되어야 한다 .
25System Software Lab.
필드와 관련 메소드들
protected URL url public URL getURL()URLConnection 이 연결하고자 하는 URL 을 가리킨다 .
try { u = new URL("http://www.ora.com/"); try { uc = u.openConnection(); System.out.println(uc.getURL()); } catch (IOException e) { System.err.println(e); } >> 결과%java printURLConnectionhttp://www.ora.com
26System Software Lab.
필드와 관련 메소드들 ( 계속 )
protected boolean connected
연결이 열려 있으면 true, 닫혀 있으면 false.URLConnection 은 생성되어도 연결되어 있지 않은 상태이므로 기본적으로 false 이다 .
27System Software Lab.
필드와 관련 메소드들 ( 계속 )protected boolean allowUserInteraction
public void setAllowUserInteraction(boolean allowuserinteraction)
public boolen getAllowUserInteraction()
사용자와의 대화가 가능한지를 지정한다 .
try { u = new URL("http://www.ora.com"); handler = new myHttpHandler(); uc = handler.openConnection(u); if (!uc.getAllowUserInteraction()) { uc.setAllowUserInteraction(true); } } catch (MalformedURLException e) { System.err.println(e); }
28System 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) ;
}
}
29System Software Lab.
필드와 관련 메소드들 ( 계속 )
protected boolean doInputpublic void setDoInput(boolean doinput)public boolean getDoInput()
try {
u = new URL("http://www.ora.com");
try {
uc = u.openConnection();
if (!uc.getDoInput()) {
uc.setDoInput(true);
}
}
catch (IOException e) {
System.err.println(e);
}
클라이언트 프로그램으로의 데이터 입력이 가능한지 체크후 능하도록 설정
30System Software Lab.
필드와 관련 메소드들 ( 계속 )
protected boolean doOutput
public void setDoInput(boolean dooutput)
public boolean getDoOutput()
try {
u = new URL("http://www.ora.com");
try {
uc = u.openConnection();
if (!uc.getDoOutput()) {
uc.setDoOutput(true);
}
}
catch (IOException e) {
System.err.println(e);
}
서버로 부터 출력작업이 가능한지 체크후 가능하도록 설정
31System Software Lab.
필드와 관련 메소드들 ( 계속 )
protected long IfModifiedSince
public void setIfModifiedSince(long ifmodifiedsince)
public long getIfModifiedSince()
try { u = new URL("http://www.ora.com"); 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())); System.out.println("Will retrieve file if it's been modified since " + new Date(uc.getIfModifiedSince()).toLocaleString()); }
>> 결과
%java last24
Will retrieve file if it's been modified since 1970-01-01 오전 9:00:00
Will retrieve file if it's been modified since 2000-05-28 오전 10:53:13
%date
2000-05-29
32System Software Lab.
필드와 관련 메소드들 ( 계속 )
pritected static boolean userCaches
public static void setUseCaches(boolean usecaches)
public static boolean getUseCaches()
로컬 캐시의 사용 여부 결정
try {
u = new URL("http://www.ora.com");
try {
uc = u.openConnection();
if (uc.getUseCaches()) {
uc.setUseCaches(false);
}
}
캐시기능의 정지
33System Software Lab.
필드와 관련 메소드들 ( 계속 )
pritected static boolean defalutUserCaches
public static void setDefaultUseCaches(boolean defaultusecaches)
public static boolean getDefaultUseCaches()
기본적으로 캐시 기능의 사용여부 선택
try {
URL u = new URL("http://www.ora.com/");
URLConnection uc = u.openConnection();
if (uc.getDefaultUseCaches()) {
uc.setDefaultUseCaches(false);
}
}
catch (IOException e) {
System.err.println(e);
}
기본적으로 캐시기능 정지
34System Software Lab.
필드와 관련 메소드들 ( 계속 )
static ContentHandlerFactory factory
public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac)
: 특정한 MIME 유형에 적합한 컨텐트 핸들러의 인스턴스 생성
text/html , image/gif파일등을 처리할 수 있는 컨텐트 핸들러를 찾을 수 있도록 알려준다 .
35System 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); }
연결확보
입력스트림을 구한다 .
배열을 읽어들인다 .
출력스트림을 구한다 .
파일로 쓰여진다 .
36System Software Lab.
유용한 프로그램들 ( 폼 데이터를 POST 방식으로 전송하기 )
void submitData() {
String query = "name=" + URLEncoder.encode("Elliotte Rusty Harold"); query += "&"; query += "email=" + URLEncoder.encode("[email protected]");
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);
연결확보
생성된 객체에 대한
출력스트림을 구한다 .
데이터를 전송한다 .
생성된 객체에 대한
입력스트림을 구한다 .
서버로 부터 응답을 읽는다 .
출력된다 .