2011년 3월 29일 화요일

HttpClient 4.x 샘플

HttpClient 3.x 위주로 사용하다가 HttpClient 4.x 버전으로 통신하는 클라이언트를 소스를 하나 만들었다. 고급스러운 건 별루 없다. 그래도 필요한 기능은 거의 포함되지 않았을까? 설명하기 귀찮다. 대충 알아서 보시길

아래의 소스 코드에는 다음과 같은 기능이 포함되어 있다.
- get / post 방식 통신
- JSESSIONID 쿠키 사용 (응답메시지, 요청메시지에서 사용)
- XML 응답 받아서 마샬링
- POST 방식의 UrlEncodedFormEntity 만들어서 요청보내기



package jaxrs;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.xml.transform.stream.StreamSource;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cxfbook.chapter4.domain.Book;
import cxfbook.chapter4.domain.BookCollection;

@ContextConfiguration(locations={"classpath*:spring/*-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class CallJaxrsTest {
  @Resource(name="jaxb2Marshaller")
  private Jaxb2Marshaller marshaller;
  
  @Test
  public void testCallJaxrs() throws Exception {
    URI uri = URIUtils.createURI("http", "localhost", 8080, "/chapter4/rest/user/book/tom/list", null, null);
    HttpGet get = new HttpGet(uri);
    get.addHeader("Accept", "application/xml");
    System.out.println("uri: " + uri);
    
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(get);
    HttpEntity entity = response.getEntity();

    
    BookCollection books = (BookCollection)
      marshaller.unmarshal(new StreamSource(entity.getContent()));
    
    for(Book book : books.getBooks()) {
      System.out.println("book: " + book);
    }
  }
  
  @Test
  public void testCallSecureService() throws Exception {
    URI uri = URIUtils.createURI("http", "localhost", 8080, "/securityweb/login.do", null, null);
    
    List parameters = new ArrayList();
    parameters.add(new BasicNameValuePair("loginId", "tom"));
    parameters.add(new BasicNameValuePair("password", "tomspasswd"));
    UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(parameters);
    
    HttpPost post = new HttpPost(uri);
    post.setEntity(reqEntity);
    
    
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(post);
    
    System.out.println("params: " + post.getParams());
    System.out.println("loginId: " + post.getParams().getParameter("loginId"));
    System.out.println("password: " + post.getParams().getParameter("password"));
    
    String jsessionId = null;
    Cookie jsessionIdCookie = null;
    for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
      System.out.println(cookie.getName() + " : " + cookie.getValue() + " - " + cookie.isExpired(new Date()));
      if("JSESSIONID".equals(cookie.getName())) {
        if(cookie.isExpired(new Date()) == false) {
          jsessionId = cookie.getValue();
          jsessionIdCookie = cookie;
        }
      }
    }
    
    System.out.println("JSESSIONID: " + jsessionId);
    
    HttpEntity entity = response.getEntity();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    entity.writeTo(out);
    
    System.out.println(new String(out.toByteArray()));
    
    System.out.println("uri: " + uri);

    
    if(jsessionId == null) {
      return;
    }

    
    System.out.println("jsessionId cookie: " + jsessionIdCookie.getClass().getName());
    System.out.println("jsessionId cookie: " + jsessionIdCookie);
    
    ObjectOutputStream cookieOutputStream = new ObjectOutputStream(new FileOutputStream("cookie.bin"));
    cookieOutputStream.writeObject(jsessionIdCookie);

    
    HttpGet get = new HttpGet("http://localhost:8080/securityweb/ws/rest/secure/user/getUser/1");
    
    ObjectInputStream cookieInputStream = new ObjectInputStream(new FileInputStream("cookie.bin"));
    jsessionIdCookie = (Cookie) cookieInputStream.readObject();
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(jsessionIdCookie);
    
    
  
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    response = httpclient.execute(get, localContext);
    
    entity = response.getEntity();
    out = new ByteArrayOutputStream();
    entity.writeTo(out);
    
    System.out.println(new String(out.toByteArray()));
  }
}

댓글 없음:

댓글 쓰기