'Http Component'에 해당되는 글 1건

[java] HttpClient - HTTP Component :: 2008/05/24 11:50

사용자 삽입 이미지
HTTP protocol을 웹브라우저나 server-side 프로그램에서가 아니라 일반 client/server의 어플리케이션에서도 사용할 수 있게 할 때 Java에서는 apache에서 제공하는 HttpClient를 사용하면 쉽게 제어할 수 있다.
Apache Group에서 제작한 컴포넌트이고 core 모듈은 Java 1.3 이상버젼에서 작동하고, non-blocking I/O 모델은 Java 5.0이상에서 작동한다.

HttpClient는 http://hc.apache.org/downloads.cgi 에서 다운로드할 수 있다.
그리고 HttpClient를 사용하기 위해서는 apache common중에서 Logging과 Codec 라이브러리가 필요하다.
각 라이브러리는 다음에서 다운로드해서 classpath로 연결시킨다.
Logging : http://commons.apache.org/downloads/dow ··· ging.cgi
Codec : http://commons.apache.org/downloads/download_codec.cgi

HttpClient의 특징

  • Standards based, pure Java, implementation HTTP verions 1.0 and 1.1
  • 확장 OO framework에 있는 모든 HTTP methods(GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE)를 완벽히 구현
  • HTTPS (HTTP over SSL) protocol 암호화를 지원
  • HTTP proxies를 통한 투명한 접속
  • CONNECT 메소드를 통해 HTTP proxies를 통과하는 tunneled HTTPS 접속구현
  • Basic, Digest authentication schemes. 단지 부분적으로 지원되는 NTLM을 참고해라.
  • custom authentication schemes를 Plug-in할 수 있는 구조
  • Pluggable secure socket factories, making it easier to use third party solutions
  • multi-threaded application에서 사용하기 위한 접속 관리 지원. Host 마다 최대접속뿐 아니라 최대 전체 접속 설정을 지원. 유효하지 않은 접속은 찾아서 닫음.
  • Set-Cookie(headers from the server and sending them back out in a Cookie: header when appropriate)를 읽음으로 자동 Cookie를 제어.
  • custom cookie 정책을 추가할 수 있는 구조
  • content body를 buffering없이 소켓을 통해 서버로 streaming하는 output stream 요청
  • 소켓을 사용해 서버로부터 직접 streaming한 응답 body를 효과적으로 읽는 input stream 응답
  • HTTP/1.0에서 KeepAlive와 HTTP/1.1에서 persistance를 사용한 지속적인 접속 유지가능
  • 서버에서 전송한 응답코드와 header를 직접 접근 가능
  • 접속 timeout 설정 지원
  • Apache License하에서 소스코드 자유롭게 공유 가능

웹페이지를 요청해서 요청한 데이터를 출력하는 예제코드

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {
  
  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
    		new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

HttpClient의 자세한 사용설명은 apache의 tutorial을 참고하세요~.










이 글은 apache http Component 사이트를 참고해서 작성했습니다.(번역이 좀 부자연스럽군. ㅡㅜ)









이올린에 북마크하기(0) 이올린에 추천하기(0)

2008/05/24 11:50 2008/05/24 11:50
Trackback Address :: http://zemy.net/tc/zemyblue/trackback/73
[로그인][오픈아이디란?]
Name
Password
Homepage

Secret