PowerPoint 프레젠테이션

Download Report

Transcript PowerPoint 프레젠테이션

10장 URLConnection 클래스
홍창범
시스템 소프트웨어 연구실
System Software Lab.
1
목차
URLConnection 클래스
- URLConnection열기
- 서버로부터 데이터를 가져오는 메소드
- 헤더의 구문 분석
- 필드와 관련 메소드
유용한 프로그램
- HTTP 연결을 통한 이진 데이터 다운로드하기
- 폼 데이터를 POST 방식으로 전송하기
System Software Lab.
2
URLConnection 클래스
URLConnection 클래스
URL에 의하여 지정되는 자원에 대한 활성화된 연결을 나타내는 추상클래스
- URL보다 서버와의 대화에 대해서 더 많이 제어.
- URLStreamHandler 클래스를 포함하는 프로토콜 핸들러 메커니즘의 일부
System Software Lab.
3
URLConnection 열기
Public URLConnection openConnection() throws IOException
로컬 호스트와 원격 호스트간 데이터가 이동할수있는 실질적 연결 생성
>> 예제
URL u;
URLConnection uc;
try {
URL u = new URL("http://www.ora.com");
try {
URLConnection uc = u.openConnection();
}
System Software Lab.
4
서버로부터 데이터를 가져오는 메소드들
Public abstract void connect() throws IOException
서버에 대해 연결을 해주는 추상 메소드
서버의 이름은 URLConnection의 생성자에게 인자로 넘겨진 후 이 클래스의 필드에 저장
되어 있는 URL로부터 추출
System Software Lab.
5
서버로부터 데이터를 가져오는 메소드들 (계속)
Public Object getContent() throws IOException
URL이 가리키는 데이터를 가져옴.
특정한 객체의 유형으로 변환(ASCII,HTML-inputStream/gif/jpg-imageProduce)
MIME헤더의 content-type을 이용.
현재 이해되는 유형 text/html, image/gif, image/jpeg 가 있다.
System Software Lab.
6
서버로부터 데이터를 가져오는 메소드들(계속)
FileInputStream
PipedInputStream
FilterInputStream
InputStream
ByteArrayInputStream
SequenceInputStream
LineNumberInputStrea
m
DataInputStream
BufferInnputStream
PushbackInputStream
StringBufferInputStream
ObjectInputStream
FileOutputStream
PipeOutputStream
OutputStream
DataOutputStream
FilterOutputStream
BufferedOutputStream
ByteArrayOutputStream
PushbackOutputStream
ObjectOutputStream
[Java.io 패키지의 입출력 스트림클래스들의 계층구조]
System Software Lab.
7
서버로부터 데이터를 가져오는 메소드들 (계속)
Public InputStream getInputStream()
- URLConnection 객체를 생성하고 그 객체에 대한 입력 스트림을 구한다.
URLConnectio
n객체생성
>>예제
uc = u.openConnection();
DataInputStream theHTML = new DataInputStream(uc.getInputStream());
Try{
while ((thisLine = theHTML.readLine()) != null) {
System.out.println(thisLine);
}
}
생성된 객체에
대한 입력스트
림을 구한다.
>> 실행결과
%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>
System Software Lab.
8
서버로부터 데이터를 가져오는 메소드들 (계속)
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);
}
System Software Lab.
9
헤더의 구문 분석
[Server]
[Client]
수신한 Request
Web 페이지를 요구
하는 HTTP Request
메세지
메세지 분석
요구된 Web 페이지
를 포함하는 HTTP
Response 메시지
생성
Request-Line
General-Header
Request-Header
Entity-Header
CRLF
Status-Line
Entity-Body
General-Header
Response-Header
Entity-Header
CRLF
전달된 페이지의
Entity-Body
디스플레이
[Server 와 Client와의 통신]
System Software Lab.
10
헤더의 구문 분석 (계속)
일반 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 인증 방법
System Software Lab.
11
헤더의 구문 분석 (계속)
[Response Header 의 예]
public String getContentType()
Server Microsoft-IIS/5.0
syssw Made By Hong_chang_bum
Cache-Control max-age=602938
public String getContentLength()
Expires Thu, 25 May 2000 15:00:00 GMT
Connection keep-alive
public String getContentEncoding()
Content-Location http://syssw/index.htm
Date Thu, 18 May 2000 15:31:01 GMT
public long getDate()
Content-Type text/html
Accept-Ranges bytes
public long getExpiration()
Last-Modified Wed, 17 May 2000 04:22:46 GMT
ETag "1685808db7bfbf1:b47"
Content-Length 213
System Software Lab.
public long LastModified()
12
헤더의 구문 분석 (계속)
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
System Software Lab.
13
헤더의 구문 분석 (계속)
4
public long getDate()
문서의 전송 날짜를 반환
5
public long getExpiration()
문서만기일을 반환
6
public long getLastModified()
문서의 최종 수정된 날짜를 반환
System Software Lab.
14
헤더의 구문 분석 (계속)
>> 예제
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
System Software Lab.
15
헤더의 구문 분석 (계속)
>> 실행결과
%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
System Software Lab.
16
임의의 MIME 헤더 필드 값을 가져오기
public String getHeaderField(String name)
인자로 넘겨진 name이라는 헤더 필드값을 반환
uc.getHeaderField(“content-type”);
uc.getHeadField(“content-encoding”);
uc.getHeadField(“date”);
uc.getHeadField(“expires”);
System Software Lab.
17
임의의 MIME 헤더 필드 값을 가져오기
public String getHeaderFieldKey(int n)
n번째 헤더의 필드키를 반환
String header5 = uc.getHeaderFieldKey(5);
System Software Lab.
18
임의의 MIME 헤더 필드 값을 가져오기
public long getHeaderFieldDate(String name, long default)
name이 가리키는 헤더 필드값을 가져와서 문자열로된 값을 long으로 변환
uc.getHeaderFieldData(“expires” , -1);
uc.getHeaderFieldData(“last-modification”, -1);
uc.getHeaderFieldData(“date”, -1);
System Software Lab.
19
임의의 MIME 헤더 필드 값을 가져오기
public String getHeaderFieldInt(String name, int default)
name의 헤더 필드의 값을 가져와 int로 변환 후 반환
int cl = uc.getHeaderFieldInt(“content-length”, -1);
System Software Lab.
20
임의의 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
System Software Lab.
21
MIME 유형 알아내기
protected static String guessContentTypeFromName(String name)
URL에서 파일이름 부분의 확장자를 기초로 하여 컨텐트 유형을 추측해낸다.
확장자는 대소문자를 구별한다.
예)
.dvi
application/x-dvi
.zip
application/zip
.tar
application/x-tar
.gif
image/gif
System Software Lab.
22
MIME 유형 알아내기 (계속)
static protected String guessContentTypeFromStream(InputStream is)
Inputstream의 최초 6바이트를 읽어 컨텐트 유형을 추측한다.
예)
GIF8
image/gif
#def
image/x-bitmap
<!
text/html
<html>
text/html
System Software Lab.
23
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)
치환하게되면, 할당된 초기값을 문자열로서 주어진 속성으로 반환되어야 한다.
System Software Lab.
24
필드와 관련 메소드들
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 printURLConnection
http://www.ora.com
System Software Lab.
25
필드와 관련 메소드들 (계속)
protected boolean connected
연결이 열려 있으면 true, 닫혀 있으면 false.
URLConnection은 생성되어도 연결되어 있지 않은 상태이므로 기본적으로 false이다.
System Software Lab.
26
필드와 관련 메소드들 (계속)
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);
}
System Software Lab.
27
필드와 관련 메소드들 (계속)
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) ;
}
}
System Software Lab.
28
필드와 관련 메소드들 (계속)
protected boolean doInput
public 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);
}
System Software Lab.
29
필드와 관련 메소드들 (계속)
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);
}
System Software Lab.
30
필드와 관련 메소드들 (계속)
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
System Software Lab.
31
필드와 관련 메소드들 (계속)
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);
}
}
System Software Lab.
32
필드와 관련 메소드들 (계속)
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);
}
System Software Lab.
33
필드와 관련 메소드들 (계속)
static ContentHandlerFactory factory
public static synchronized void setContentHandlerFactory(ContentHandlerFactory
fac)
: 특정한 MIME 유형에 적합한 컨텐트 핸들러의 인스턴스 생성
text/html , image/gif파일등을 처리할 수 있는 컨텐트 핸들러를 찾을 수 있도록 알려준다.
System Software Lab.
34
유용한 프로그램들
(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 + "
System.err.println("Expected " + cl + " bytes");
}
입력스트림을
구한다.
배열을 읽어
들인다.
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);
진다.
}
System Software Lab.
출력스트림을
구한다.
35
유용한 프로그램들
(폼 데이터를 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);
서버로 부터 응
생성된 객체에
대한 입력스트
림을 구한다.
답을 읽는다.
출력된다.
System Software Lab.
36