* 4.3 참고 : http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/index.html
* 설정
BasicHttpParams params = new BasicHttpParams();
// Deprecated.(4.3) -> org.apache.http.config ( ConnectionConfig, SocketConfig ... )
ConnManagerParams.setTimeout( params, 10000 );
ConnManagerParams.setMaxConnectionsPerRoute( params, new ConnPerRouteBean( 10 ) );
ConnManagerParams.setMaxTotalConnections( params, 5);
HttpConnectionParams.setConnectionTimeout( params, 10000 );
HttpConnectionParams.setSoTimeout( params, 10000 );
HttpConnectionParams.setTcpNoDelay( params, true );
HttpProtocolParams.setVersion( params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUserAgent( params, " " );
// 스키마 등록
SchemeRegistry scheme = new SchemeRegistry();
// Deprecated.(4.3) -> Registry
scheme.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
scheme.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// Deprecated.(4.3) -> PlainConnectionSocketFactory, SSLConnectionSocketFactory
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(1000)
.setConnectTimeout(1000)
.build();
HttpGet httpget = new HttpGet( "http://url/path?param=value");
httpget.setConfig( requestConfig );
// client 에 직접 적용하는 경우
httpClient.setDefaultRequestConfig( requestConfig );
CacheConfig cacheConfig = CacheConfig.custom()
.setMaxCacheEntries(1000)
.setMaxObjectSize(8192)
.build();
httpClient.setCacheConfig( cacheConfig );
// cache의 경우 client execute 이후에 HttpCacheContext 를 사용해 핸들링한다.
.
.
// 스키마 등록
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
.register( "http", PlainConnectionSocketFactory.getSocketFactory() )
.register( "https", SSLConnectionSocketFactory.getSocketFactory() )
.build();
* Client
DefaultHttpClient httpClient = new DefaultHttpClient( man, params );
// Deprecated.(4.3) -> CloseableHttpClient , HttpClientBuilder.create().build(); , HttpClients
// 인터셉터
httpClient.addRequestInterceptor( new HttpRequestInterceptor() {
public void process( HttpRequest request, HttpContext context ) {
}
});
httpClient.addResponseInterceptor( new HttpResponseInterceptor() {
public void process( HttpResponse response, HttpContext context ) {
}
});
// default client is CloseableHttpClient
HttpClient httpClient = HttpClientBuilder.create().build();
HttpClient httpClient = HttpClients.createDefault();
// 인터셉터
CloseableHttpClient httpClient = HttpClients.custom()
.addInterceptorLast( new HttpRequestInterceptor() {
public void process( HttpRequest request, HttpContext context ) {
}
}).build();
// keep alive
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() {
};
HttpClient httpClinet = HttpClinetBuilder.create()
.setKeepAliveStrategy( keepAliveStrat )
.build();
* 요청 / 응답
PostMethod post = new PostMethod();
GetMethod get = new GetMethod();
// deprecated -> HttpPost , HttpGet
// 요청
post.setPath( url );
post.setRequestHeader( key, value );
post.setRequestBody( message );
// 응답
Header[] header = post.getResponseHeader();
String body = post.getResponseBodyAsString();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost( url );
// HttpGet httpGet = new HttpGet( url );
// header
httpPost.addHeader( key, value );
// body
// html form
ArrayList<NameValuePair> nameValue = new ArrayList<NameValuePair>();
nameValue.add( new BasicNameValuePair("name", "value" );
UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity( nameValue, Consts.UTF-8);
// json string body
StringEntity reqEntity = new StringEntity( json, ContextType.create("text/plain", "UTF-8"));
// file
File file = new File("test.txt");
FileEntity reqEntity = new FileEntity( file, ContentType.create("text/plain", "UTF-8"));
httpPost.setEntity( reqEntity );
// 응답
HttpResponse response = httpClient.execute( httpPost );
Header[] header = response.getAllHeaders();
HttpEntity entity = response.getEntity();
long len = entity.getContentLength();
// read body(text)
String line;
StringBuffer buffer = new StringBuffer();
InputStream in = entity.getContent();
InputStreamReader isr = new InputStreamReader( in );
BufferedReader reader = new BufferedReader( isr );
while( ( line = reader.readLine() != null ) {
buffer.append(line);
}
in.close();
httpPost.releaseConnection();
// Uri 사용
URI uri = new URIBuilder()
.setScheme("http")
.setHost("url")
.setPath("/path")
.setParameter("param", "value")
.build();
HttpGet httpget = new HttpGet(uri);
* pooling 커넥션 관리자
ThreadSafeClientConnManager man = new ThreadSafeClientConnManager( params, scheme );
// Deprecated.(4.2) -> PoolingHttpClientConnectionManager
PoolingHttpClinetConnectionManager man = new PoolingHttpClientConnectionManager();
man.setMaxTotal(200);
man.setDefaultMaxPerRoute(20);
* 컨텍스트
HttpContext httpContext = new SyncBasicHttpContext( new BasicHttpContext() );
// Deprecated.(4.2) -> HttpContext는 쓰레드간에 공유될수 없음.
// 연결 요청
PoolingHttpClinetConnectionManager man = new PoolingHttpClientConnectionManager();
HttpClientContext context = HttpClientContext.create();
HttpRoute route = new HttpRoute( new HttpHost( "url", 80 ));
ConnectionRequest connRequest = man.requestConnection( rount, null);
HttpClientConnection conn = connRequest.get( 10, TimeUnit.SECONDS );
if( !conn.isOpen() ) {
man.connect( conn, route, 1000, context );
man.routeComplete( conn, route, context );
}
man.releaseConnection( conn, null, 1, TimeUnit.MINUTES );
* 소켓
HttpClientContext clinetContext = HttpClientContext.create();
PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
Socket socket = sf.createSocket( clientContext );
InetSocketAddress remote = new InetSocketAddress(
InetAddress.getByAddress( new byet[]{127,0,0,1}), 80);
sf.connectSocket( 1000, socket, new HttpHost("localhost"), remote, null, clientContext);
'프로그래밍 > JAVA' 카테고리의 다른 글
[eclipse] eclipse 4 platform (0) | 2014.03.17 |
---|---|
Annotation (0) | 2014.03.15 |
[swt] 이벤트 (0) | 2014.03.14 |
[eclipse] Extention Points (0) | 2014.03.14 |
[eclipse] simple plug-in example (0) | 2014.03.13 |
[JAVA TV] MHP 배경이미지 처리 (0) | 2013.12.27 |
[JAVA TV] 타이머 (0) | 2013.12.27 |
[awt] 이미지 읽기~ (0) | 2013.12.17 |
GSON 간단 사용 예 (0) | 2013.09.12 |
CRC16-CCITT crc생성함수 (0) | 2012.10.04 |