List of usage examples for org.apache.http.protocol HttpCoreContext create
public static HttpCoreContext 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);/* ww w. j a v a 2 s .com*/ 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: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);/*w ww .j a v a 2s. 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: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);/*ww w.ja va2 s. 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.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);/*from w w w . j ava2 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();/*from www .j a va2s . c o m*/ // 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.oracle.jes.samples.hellostorage.HttpElementPost.java
public void putData2() 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("192.168.1.5", 8080); coreContext.setTargetHost(host);// ww w . j a v a 2 s . c om DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try { HttpEntity[] requestBodies = { new StringEntity("This is the first test request", ContentType.create("text/plain", Consts.UTF_8)), new ByteArrayEntity("This is the second test request".getBytes("UTF-8"), ContentType.APPLICATION_OCTET_STREAM), new InputStreamEntity( new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), ContentType.APPLICATION_OCTET_STREAM) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[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:com.lion328.xenonlauncher.proxy.HttpDataHandler.java
@Override public boolean process(Socket client, Socket server) throws Exception { InputStream clientIn = client.getInputStream(); clientIn.mark(65536);/*from w ww .ja va 2 s .co m*/ try { DefaultBHttpServerConnection httpClient = new DefaultBHttpServerConnection(8192); httpClient.bind(client); httpClient.setSocketTimeout(timeout); DefaultBHttpClientConnection httpServer = new DefaultBHttpClientConnection(8192); httpServer.bind(server); HttpCoreContext context = HttpCoreContext.create(); context.setAttribute("client.socket", client); context.setAttribute("server.socket", server); HttpEntityEnclosingRequest request; do { HttpRequest rawRequest = httpClient.receiveRequestHeader(); if (rawRequest instanceof HttpEntityEnclosingRequest) { request = (HttpEntityEnclosingRequest) rawRequest; } else { request = new BasicHttpEntityEnclosingRequest(rawRequest.getRequestLine()); request.setHeaders(rawRequest.getAllHeaders()); } httpClient.receiveRequestEntity(request); HttpResponse response = new BasicHttpResponse( new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); boolean sent = false; for (Map.Entry<Integer, HttpRequestHandler> entry : handlers.entrySet()) { entry.getValue().handle(request, response, context); if (context.getAttribute("response.set") instanceof HttpResponse) { response = (HttpResponse) context.getAttribute("response.set"); } if (context.getAttribute("pipeline.end") == Boolean.TRUE) { break; } if (context.getAttribute("response.need-original") == Boolean.TRUE && !sent) { httpServer.sendRequestHeader(request); httpServer.sendRequestEntity(request); response = httpServer.receiveResponseHeader(); httpServer.receiveResponseEntity(response); entry.getValue().handle(request, response, context); context.removeAttribute("response.need-original"); context.setAttribute("request.sent", true); sent = true; } } if (context.getAttribute("response.sent") != Boolean.TRUE) { httpClient.sendResponseHeader(response); if (response.getEntity() != null) { httpClient.sendResponseEntity(response); } } } while (request.getFirstHeader("Connection").getValue().equals("keep-alive")); return true; } catch (ProtocolException e) { clientIn.reset(); return false; } catch (ConnectionClosedException e) { return true; } }
From source file:us.pserver.revok.channel.HttpResponseChannel.java
/** * Init some objects for http communication. *///from w w w . j a va2 s .com private void init() { context = HttpCoreContext.create(); processor = HttpProcessorBuilder.create().add(new ResponseServer(HttpConsts.HD_VAL_SERVER)) .add(new ResponseDate()).add(new ResponseContent()).add(new ResponseConnControl()).build(); }
From source file:us.pserver.revok.channel.HttpRequestChannel.java
/** * Init some objects for http communication. *///from w w w . j a va2 s.c om private void init() { algo = CryptAlgorithm.AES_CBC_PKCS5; context = HttpCoreContext.create(); context.setTargetHost( new HttpHost((netc.getAddress() == null ? "localhost" : netc.getAddress()), netc.getPort())); processor = HttpProcessorBuilder.create().add(new RequestContent()).add(new RequestTargetHost()) .add(new RequestUserAgent(HttpConsts.HD_VAL_USER_AGENT)).add(new RequestConnControl()).build(); }