List of usage examples for org.apache.http.nio.protocol HttpAsyncRequester HttpAsyncRequester
@Deprecated public HttpAsyncRequester(final HttpProcessor httpprocessor, final ConnectionReuseStrategy reuseStrategy, final HttpParams params)
From source file:com.weibo.wesync.client.NHttpClient2.java
public static void main(String[] args) throws Exception { RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem"); // /*from w w w . ja v a2s .c o m*/ byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes()); password = RSAEncrypt.toHexString(cipher); // HTTP parameters for the client HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params); // Create client-side I/O reactor IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(1); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(1); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HttpAsyncRequester requester = new HttpAsyncRequester( // httpproc, new DefaultConnectionReuseStrategy(), params); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), new HttpHost("123.125.106.28", 8082, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); int callbackId = 0; for (int i = 0; i < 1; i++) { for (final HttpHost target : targets) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync"); // String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes()); // request.setHeader("authorization", "Basic " + usrpwd); request.setHeader("uid", "2565640713"); Meyou.MeyouPacket packet = null; if (callbackId == 0) { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.notice).build(); } else { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.wesync).build(); } ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray()); request.setEntity(entity); // BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html"); System.out.println("send ..."); HttpAsyncRequester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, new BasicHttpContext(), // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code == 200) { try { latch.countDown(); DataInputStream in; in = new DataInputStream(response.getEntity().getContent()); int packetLength = in.readInt(); int start = 0; while (packetLength > 0) { ByteArrayOutputStream outstream = new ByteArrayOutputStream( packetLength); byte[] buffer = new byte[1024]; int len = 0; while (start < packetLength && (len = in.read(buffer, start, packetLength)) > 0) { outstream.write(buffer, 0, len); start += len; } Meyou.MeyouPacket packet0 = Meyou.MeyouPacket .parseFrom(outstream.toByteArray()); System.out.println(target + "->" + packet0); if ((len = in.read(buffer, start, 4)) > 0) { packetLength = Util.readPacketLength(buffer); } else { break; } } } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("error code=" + code + "|" + status.getReasonPhrase()); } } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); Thread.sleep((long) (Math.random() * 10000)); } } // latch.await(); // System.out.println("Shutting down I/O reactor"); // ioReactor.shutdown(); // System.out.println("Done"); }
From source file:com.comcast.cns.io.HTTPEndpointAsyncPublisher.java
@Override public void send() throws Exception { HttpAsyncRequester requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy(), httpParams);/*w ww. j a va 2s .c o m*/ final URL url = new URL(endpoint); final HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getPath() + (url.getQuery() == null ? "" : "?" + url.getQuery())); composeHeader(request); String msg = null; if (message.getMessageStructure() == CNSMessageStructure.json) { msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http); } else { msg = message.getMessage(); } if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) { msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http); } logger.debug("event=send_async_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\""); request.setEntity(new NStringEntity(msg)); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), connectionPool, new BasicHttpContext(), new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { int statusCode = response.getStatusLine().getStatusCode(); // accept all 2xx status codes if (statusCode >= 200 && statusCode < 300) { callback.onSuccess(); } else { logger.warn(target + "://" + url.getPath() + "?" + url.getQuery() + " -> " + response.getStatusLine()); callback.onFailure(statusCode); } } public void failed(final Exception ex) { logger.warn(target + " " + url.getPath() + " " + url.getQuery(), ex); callback.onFailure(0); } public void cancelled() { logger.warn(target + " " + url.getPath() + " " + url.getQuery() + " -> " + "cancelled"); callback.onFailure(1); } }); }
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpAsyncClient.java
private void initialize() { if (initialized.getAndSet(true)) { return;// www . j av a 2 s.co m } // HTTP parameters for the client final HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.timeout", 30000)); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000)); params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024)); params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.valueOf(System.getProperty("com.googlecode.jsonrpc4j.async.tcp.nodelay", "true"))); params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0"); // Create client-side I/O reactor final ConnectingIOReactor ioReactor; try { IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(Integer.getInteger("com.googlecode.jsonrpc4j.async.reactor.threads", 1)); ioReactor = new DefaultConnectingIOReactor(config); } catch (IOReactorException e) { throw new RuntimeException("Exception initializing asynchronous Apache HTTP Client", e); } // Create a default SSLSetupHandler that accepts any certificate if (sslContext == null) { try { sslContext = SSLContext.getDefault(); } catch (Exception e) { throw new RuntimeException(e); } } // Create HTTP connection pool BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, params); pool = new BasicNIOConnPool(ioReactor, nioConnFactory, params); // Limit total number of connections to 500 by default pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500)); pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500)); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext, params); // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } } }, "jsonrpc4j HTTP IOReactor"); // Start the client thread t.setDaemon(true); t.start(); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create HTTP requester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); }