3.0의 내용이지만 3.1만에서도 같다.
물론 4.0은 다르다
목차
1. 설치 및 설명
2. getMethod
3. postMethod
4. Header 설정
5. Cookie 설정
기타. 1) Reference
#### 1. 설명 및 설치
1-1. HttpClient 소개
HttpClient은 HTTP상에서 커뮤니케이션을 하는 자바 기반의 어플리케이션 개발을 쉽게 할수 있도록 제공한다.
우리가 웹 브라우저 또는 그에 준하는 어플리케이션을 개발한다면 HttpClient은 우리에게 클라이언트 코드 개발에 도움을 줄수있다.
이름에서 의미하는것과 같이 HttpClient는 오직 HTTP 클라이언트 코드을 위한 컴포넌트이지 HTTP 요청을 처리하는 서버측 프로세스을 지원하지는 않는다.
1-2. 설치
현재 아파치 HttpClient 는 3.0.1 안정버전을 지원한다.
Jakarta Commons HttpClient 페이지에서 다운로드 받으면 된다.
(다운로드 페이지: http://jakarta.apache.org/commons/httpclient/downloads.html)
(최신버전 다운로드:
- http://jakarta.apache.org/site/downloads/downloads_commons-httpclient.cgi
- http://mirror.apache-kr.org/jakarta/commons/httpclient/binary/commons-httpclient-3.0.1.zip
)
commons-httpclient-3.0.1.zip 를 받아서 압축을 풀고,
commons-httpclient-3.0.1.jar 를 CLASSPATH 에 추가하면 된다.
1-3. 추가 설정(Dependencies)
http://jakarta.apache.org/commons/httpclient/dependencies.html
Artifact ID Type Version Scope URL Comment
commons-codec jar 1.2 http://jakarta.apache.org/commons/codec/
http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi
commons-logging jar 1.0.4 http://jakarta.apache.org/commons/logging/
junit jar 3.8.1 test http://www.junit.org/
#### 2. getMethod 사용 예제
=========================== GetSample.java =================================
package test.httpclient;
import java.io.FileOutputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
// Get Method를 사용한 예제
public class GetSample {
// 가져올 페이지 주소, 네이버 뉴스 속보
private static String url =
"http://news.naver.com/news/list.php";
// 파일에 byte[] 저장
public static void saveBytes(String filepath, byte[] byteData) throws Exception
{
FileOutputStream foStream = null;
try {
foStream = new FileOutputStream(filepath);
foStream.write(byteData);
} finally {
try { foStream.close(); foStream = null; } catch (Exception e) {}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// HttpClient 생성
HttpClient client = new HttpClient();
// 요청 Method 지정
HttpMethod method = new GetMethod(url);
try {
// QueryString 지정, 1.문자열
url = url + "?mode=LSD§ion_id=001&menu_id=001&view=1";
// QueryString 지정, 2.NameValuePair 사용
// NameValuePair nvp1= new NameValuePair("mode","LSD");
// NameValuePair nvp2= new NameValuePair("section_id","001");
// NameValuePair nvp3= new NameValuePair("menu_id","001");
// NameValuePair nvp4= new NameValuePair("view","1");
// method.setQueryString(new NameValuePair[]{nvp1,nvp2, nvp3, nvp4});
System.out.println("QueryString>>> "+method.getQueryString());
// HTTP 요청 및 요청 결과
int statusCode = client.executeMethod(method);
// 요청 결과..
if (statusCode == HttpStatus.SC_OK) {
System.out.println("요청 성공");
System.out.println("응답 HTML:\n" + method.getResponseBodyAsString());
// 결과 저장
GetSample.saveBytes("naver_news.html", method.getResponseBody());
} else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||
(statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||
(statusCode == HttpStatus.SC_SEE_OTHER) ||
(statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
System.out.println("Redirecte !!!");
System.out.println("Redirect target: " + method.getResponseHeader("location").getValue());
}
} catch (Exception e) {
e.printStackTrace();
// Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
// commons-logging.jar, commons-logging-api.jar 를 CLASSPATH에 추가한다.
// Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException
// commons-codec-1.3.jar 를 CLASSPATH에 추가한다.
}
}
}
=========================== GetSample.java =================================
#### 3. postMethod 사용
GetMethod 나 PostMethod 나 사용방법은 비슷합니다.
PostMethod method = new PostMethod("http://xx.com/ex_login_ok.php");
NameValuePair userid = new NameValuePair("nick", "aaaaa");
NameValuePair userpw = new NameValuePair("password", "bbbb");
method.setRequestBody( new NameValuePair[] {userid, userpw});
client.executeMethod(method);
#### 4. Header 사용
헤더를 사용하기 위해서는 setRequestHeader() 를 이용하여 원하는 헤더를 정의해 주시면 됩니다.
String charset = null; // 기존 charset 사용
//String charset = "euc_kr"; // charset 지정
// 요청 헤더 설정
if (charset == null) {
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
} else {
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);
}
#### 5. Cookie 사용
아직 정리가 않되서.. 분량이 좀 많네요.^^;
찬찬히 정리하겠습니다.
#### Reference
1) 자카르타 프로젝트 HttpClient와 FileUpload 사용하기
- http://blog.empas.com/inter999/read.html?a=3271313&l=1&v=trackback