List of usage examples for org.apache.http.protocol HttpProcessorBuilder create
public static HttpProcessorBuilder create()
From source file:com.alexjalg.gson_google.EjecutarHttpClient.java
public static void main(String[] args) throws Exception { HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent()) .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext = HttpCoreContext.create(); HttpHost host = new HttpHost("jsonplaceholder.typicode.com", 80); coreContext.setTargetHost(host);//from w w w . j a v a 2s .c o m DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try { String[] targets = { "/posts" }; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); httpexecutor.preProcess(request, httpproc, coreContext); HttpResponse response = httpexecutor.execute(request, conn, coreContext); httpexecutor.postProcess(response, httpproc, coreContext); System.out.println("<< Response: " + response.getStatusLine()); // System.out.println(EntityUtils.toString(response.getEntity())); String json = EntityUtils.toString(response.getEntity()); ArrayList<Posts> listPosts = new ArrayList<Posts>(); Type listType = new TypeToken<ArrayList<Posts>>() { }.getType(); listPosts = new Gson().fromJson(json, listType); for (Posts post : listPosts) { System.out.println(""); System.out.println(post.getUserId()); System.out.println(post.getId()); System.out.println(post.getTitle()); System.out.println(post.getBody()); } System.out.println("=============="); if (!connStrategy.keepAlive(response, coreContext)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:httpscheduler.HttpScheduler.java
/** * @param args the command line arguments * @throws java.lang.Exception//from w w w . j av a 2s . c o m */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Invalid command line parameters for worker"); System.exit(-1); } int fixedExecutorSize = 4; //Creating fixed size executor ThreadPoolExecutor taskCommExecutor = new ThreadPoolExecutor(fixedExecutorSize, fixedExecutorSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); // Used for late binding JobMap jobMap = new JobMap(); // Set port number int port = Integer.parseInt(args[0]); // Set worker mode String mode = args[1].substring(2); // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); // Different handlers for late binding and generic cases if (mode.equals("late")) reqistry.register("*", new LateBindingRequestHandler(taskCommExecutor, jobMap)); else reqistry.register("*", new GenericRequestHandler(taskCommExecutor, mode)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; // create a thread to listen for possible client available connections Thread t; if (mode.equals("late")) t = new LateBindingRequestListenerThread(port, httpService, sf); else t = new GenericRequestListenerThread(port, httpService, sf); System.out.println("Request Listener Thread created"); t.setDaemon(false); t.start(); // main thread should wait for the listener to exit before shutdown the // task executor pool t.join(); // shutdown task executor pool and wait for any taskCommExecutor thread // still running taskCommExecutor.shutdown(); while (!taskCommExecutor.isTerminated()) { } System.out.println("Finished all task communication executor threads"); System.out.println("Finished all tasks"); }
From source file:cn.heroes.ud.protocol.ElementalHttpGet.java
public static void main(String[] args) throws Exception { HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent()) .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext = HttpCoreContext.create(); HttpHost host = new HttpHost("localhost", 8080); coreContext.setTargetHost(host);//from ww w. j ava 2 s . co m DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try { String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" }; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); httpexecutor.preProcess(request, httpproc, coreContext); HttpResponse response = httpexecutor.execute(request, conn, coreContext); httpexecutor.postProcess(response, httpproc, coreContext); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, coreContext)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:net.minder.httpcap.HttpCap.java
public static void main(String[] args) throws Exception { PropertyConfigurator.configure(ClassLoader.getSystemResourceAsStream("log4j.properties")); int port = DEFAULT_PORT; if (args.length > 0) { try {//from w w w. j a va 2 s .c o m port = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { port = DEFAULT_PORT; } } HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("HttpCap/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpCapHandler()); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; // if (port == 8443) { // // Initialize SSL context // ClassLoader cl = HttpCap.class.getClassLoader(); // URL url = cl.getResource("my.keystore"); // if (url == null) { // System.out.println("Keystore not found"); // System.exit(1); // } // KeyStore keystore = KeyStore.getInstance("jks"); // keystore.load(url.openStream(), "secret".toCharArray()); // KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( // KeyManagerFactory.getDefaultAlgorithm()); // kmfactory.init(keystore, "secret".toCharArray()); // KeyManager[] keymanagers = kmfactory.getKeyManagers(); // SSLContext sslcontext = SSLContext.getInstance("TLS"); // sslcontext.init(keymanagers, null, null); // sf = sslcontext.getServerSocketFactory(); // } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:com.vikram.kdtree.ElementalHttpServer.java
public static void main(String[] args) throws Exception { // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build();//from ww w.ja va 2s . c o m // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpPostReceiver()); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); Properties properties = new Properties(); properties.load(new FileInputStream("Config.properties")); Thread t = new RequestListenerThread(Integer.valueOf(properties.getProperty("requestPort")), httpService, null); t.setDaemon(false); t.start(); }
From source file:com.yulore.demo.NHttpClient.java
public static void main(String[] args) throws Exception { // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create() // Use standard client-side protocol interceptors .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl()) .add(new RequestUserAgent("Test/1.1")).add(new RequestExpectContinue(true)).build(); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, ConnectionConfig.DEFAULT);/* www . j a va 2 s.c o m*/ // Create client-side I/O reactor final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(2); // 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); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { new HttpHost("www.apache.org", 80, "http"), new HttpHost("www.verisign.com", 443, "https"), new HttpHost("www.google.com", 80, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); for (final HttpHost target : targets) { BasicHttpRequest request = new BasicHttpRequest("GET", "/"); HttpCoreContext coreContext = HttpCoreContext.create(); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, coreContext, // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(target + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); } latch.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
From source file:framework.httpclient.nio.NHttpClient.java
public static void main(String[] args) throws Exception { // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create() // Use standard client-side protocol interceptors .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl()) .add(new RequestUserAgent("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true)) .build();/* w w w . j a v a2s.c om*/ // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch // IO final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, ConnectionConfig.DEFAULT); // Create client-side I/O reactor // IO reactor final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); // Create HTTP connection pool // HTTP BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(2); // 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 // HTTP HttpAsyncRequester requester = new HttpAsyncRequester(httpproc); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"), // new HttpHost("www.zhihu.com", -1, "https"), new HttpHost("www.bilibili.com", -1, "https") }; final CountDownLatch latch = new CountDownLatch(targets.length); for (final HttpHost target : targets) { BasicHttpRequest request = new BasicHttpRequest("GET", "/"); HttpCoreContext coreContext = HttpCoreContext.create(); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, coreContext, // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(target + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.err.println(target + "->" + ex); ex.printStackTrace(); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); } latch.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
From source file:com.adhi.webserver.WebServer.java
public static void main(String[] args) throws Exception { int port = 9999; // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build();/*from w w w. j a v a2 s. c om*/ // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new MessageCommandHandler()); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = WebServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }
From source file:proxy.ElementalHttpGet.java
public static void main(String[] args) throws Exception { // String localIp = args[0]; // System.out.println("localIp: " + localIp); HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent()) .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext = HttpCoreContext.create(); HttpHost host = new HttpHost("api.weibo.com", 443, "https"); coreContext.setTargetHost(host);//from ww w . ja va 2s .c om // for (InetAddress localinetAddress : getAllIp("eth0")) { // System.out.println(localinetAddress.getHostAddress()); request(httpproc, httpexecutor, coreContext, host, InetAddress.getByName("60.169.74.152")); // } }
From source file:com.bfd.job.testClient.t04.ElementalHttpServer.java
public static void main(String[] args) throws Exception { /**/*from w ww . j a v a2 s . c o m*/ * if (args.length < 1) { * System.err.println("Please specify document root directory"); * System.exit(1); } // Document root directory String docRoot = * args[0]; */ String docRoot = "c:/root"; int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = ElementalHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } Thread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); }