2
* $HeadURL: https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.0.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpSSLClient.java $
4
* $Date: 2009-02-14 17:38:14 +0100 (Sat, 14 Feb 2009) $
6
* ====================================================================
7
* Licensed to the Apache Software Foundation (ASF) under one
8
* or more contributor license agreements. See the NOTICE file
9
* distributed with this work for additional information
10
* regarding copyright ownership. The ASF licenses this file
11
* to you under the Apache License, Version 2.0 (the
12
* "License"); you may not use this file except in compliance
13
* with the License. You may obtain a copy of the License at
15
* http://www.apache.org/licenses/LICENSE-2.0
17
* Unless required by applicable law or agreed to in writing,
18
* software distributed under the License is distributed on an
19
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
20
* KIND, either express or implied. See the License for the
21
* specific language governing permissions and limitations
23
* ====================================================================
25
* This software consists of voluntary contributions made by many
26
* individuals on behalf of the Apache Software Foundation. For more
27
* information on the Apache Software Foundation, please see
28
* <http://www.apache.org/>.
31
package org.apache.http.examples.nio;
33
import java.io.IOException;
34
import java.io.InterruptedIOException;
35
import java.net.InetSocketAddress;
36
import java.util.concurrent.CountDownLatch;
38
import javax.net.ssl.SSLContext;
40
import org.apache.http.HttpEntity;
41
import org.apache.http.HttpException;
42
import org.apache.http.HttpHost;
43
import org.apache.http.HttpRequest;
44
import org.apache.http.HttpResponse;
45
import org.apache.http.impl.DefaultConnectionReuseStrategy;
46
import org.apache.http.impl.nio.SSLClientIOEventDispatch;
47
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
48
import org.apache.http.message.BasicHttpRequest;
49
import org.apache.http.nio.NHttpConnection;
50
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
51
import org.apache.http.nio.protocol.EventListener;
52
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
53
import org.apache.http.nio.reactor.ConnectingIOReactor;
54
import org.apache.http.nio.reactor.IOEventDispatch;
55
import org.apache.http.nio.reactor.SessionRequest;
56
import org.apache.http.nio.reactor.SessionRequestCallback;
57
import org.apache.http.params.BasicHttpParams;
58
import org.apache.http.params.CoreConnectionPNames;
59
import org.apache.http.params.HttpParams;
60
import org.apache.http.params.CoreProtocolPNames;
61
import org.apache.http.protocol.BasicHttpProcessor;
62
import org.apache.http.protocol.ExecutionContext;
63
import org.apache.http.protocol.HttpContext;
64
import org.apache.http.protocol.RequestConnControl;
65
import org.apache.http.protocol.RequestContent;
66
import org.apache.http.protocol.RequestExpectContinue;
67
import org.apache.http.protocol.RequestTargetHost;
68
import org.apache.http.protocol.RequestUserAgent;
69
import org.apache.http.util.EntityUtils;
72
* Elemental example for executing HTTPS requests using the non-blocking I/O model.
74
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
75
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
78
* @version $Revision: 744516 $
80
public class NHttpSSLClient {
82
public static void main(String[] args) throws Exception {
83
HttpParams params = new BasicHttpParams();
85
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
86
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
87
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
88
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
89
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
90
.setParameter(CoreProtocolPNames.USER_AGENT, "Jakarta-HttpComponents-NIO/1.1");
92
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);
94
BasicHttpProcessor httpproc = new BasicHttpProcessor();
95
httpproc.addInterceptor(new RequestContent());
96
httpproc.addInterceptor(new RequestTargetHost());
97
httpproc.addInterceptor(new RequestConnControl());
98
httpproc.addInterceptor(new RequestUserAgent());
99
httpproc.addInterceptor(new RequestExpectContinue());
101
// Initialize default SSL context
102
SSLContext sslcontext = SSLContext.getInstance("SSL");
103
sslcontext.init(null, null, null);
105
// We are going to use this object to synchronize between the
106
// I/O event and main threads
107
CountDownLatch requestCount = new CountDownLatch(3);
109
BufferingHttpClientHandler handler = new BufferingHttpClientHandler(
111
new MyHttpRequestExecutionHandler(requestCount),
112
new DefaultConnectionReuseStrategy(),
115
handler.setEventListener(new EventLogger());
117
final IOEventDispatch ioEventDispatch = new SSLClientIOEventDispatch(
122
Thread t = new Thread(new Runnable() {
126
ioReactor.execute(ioEventDispatch);
127
} catch (InterruptedIOException ex) {
128
System.err.println("Interrupted");
129
} catch (IOException e) {
130
System.err.println("I/O error: " + e.getMessage());
132
System.out.println("Shutdown");
138
SessionRequest[] reqs = new SessionRequest[3];
139
reqs[0] = ioReactor.connect(
140
new InetSocketAddress("www.netscape.com", 443),
142
new HttpHost("www.netscape.com", 443),
143
new MySessionRequestCallback(requestCount));
144
reqs[1] = ioReactor.connect(
145
new InetSocketAddress("www.verisign.com", 443),
147
new HttpHost("www.verisign.com", 443),
148
new MySessionRequestCallback(requestCount));
149
reqs[2] = ioReactor.connect(
150
new InetSocketAddress("www.yahoo.com", 443),
152
new HttpHost("www.yahoo.com", 443),
153
new MySessionRequestCallback(requestCount));
155
// Block until all connections signal
156
// completion of the request execution
157
requestCount.await();
159
System.out.println("Shutting down I/O reactor");
161
ioReactor.shutdown();
163
System.out.println("Done");
166
static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
168
private final static String REQUEST_SENT = "request-sent";
169
private final static String RESPONSE_RECEIVED = "response-received";
171
private final CountDownLatch requestCount;
173
public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) {
175
this.requestCount = requestCount;
178
public void initalizeContext(final HttpContext context, final Object attachment) {
179
HttpHost targetHost = (HttpHost) attachment;
180
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
183
public void finalizeContext(final HttpContext context) {
184
Object flag = context.getAttribute(RESPONSE_RECEIVED);
186
// Signal completion of the request execution
187
this.requestCount.countDown();
191
public HttpRequest submitRequest(final HttpContext context) {
192
HttpHost targetHost = (HttpHost) context.getAttribute(
193
ExecutionContext.HTTP_TARGET_HOST);
194
Object token = context.getAttribute(REQUEST_SENT);
196
// Stick some object into the context
197
context.setAttribute(REQUEST_SENT, Boolean.TRUE);
199
System.out.println("--------------");
200
System.out.println("Sending request to " + targetHost);
201
System.out.println("--------------");
203
return new BasicHttpRequest("GET", "/");
205
// No new request to submit
210
public void handleResponse(final HttpResponse response, final HttpContext context) {
211
HttpEntity entity = response.getEntity();
213
String content = EntityUtils.toString(entity);
215
System.out.println("--------------");
216
System.out.println(response.getStatusLine());
217
System.out.println("--------------");
218
System.out.println("Document length: " + content.length());
219
System.out.println("--------------");
220
} catch (IOException ex) {
221
System.err.println("I/O error: " + ex.getMessage());
224
context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE);
226
// Signal completion of the request execution
227
this.requestCount.countDown();
232
static class MySessionRequestCallback implements SessionRequestCallback {
234
private final CountDownLatch requestCount;
236
public MySessionRequestCallback(final CountDownLatch requestCount) {
238
this.requestCount = requestCount;
241
public void cancelled(final SessionRequest request) {
242
System.out.println("Connect request cancelled: " + request.getRemoteAddress());
243
this.requestCount.countDown();
246
public void completed(final SessionRequest request) {
249
public void failed(final SessionRequest request) {
250
System.out.println("Connect request failed: " + request.getRemoteAddress());
251
this.requestCount.countDown();
254
public void timeout(final SessionRequest request) {
255
System.out.println("Connect request timed out: " + request.getRemoteAddress());
256
this.requestCount.countDown();
261
static class EventLogger implements EventListener {
263
public void connectionOpen(final NHttpConnection conn) {
264
System.out.println("Connection open: " + conn);
267
public void connectionTimeout(final NHttpConnection conn) {
268
System.out.println("Connection timed out: " + conn);
271
public void connectionClosed(final NHttpConnection conn) {
272
System.out.println("Connection closed: " + conn);
275
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
276
System.err.println("I/O error: " + ex.getMessage());
279
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
280
System.err.println("HTTP error: " + ex.getMessage());