public RequestListenerThread(int port, final String docroot) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024).setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true).setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[]{ new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler()); // Set up the HTTP service this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
private void initHttpClient() { _params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(_params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(_params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(_params, false); HttpProtocolParams.setHttpElementCharset(_params, "UTF-8"); _httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new BasicHttpProcessor(), new RequestConnControl(), new RequestContent(), new RequestDate(), new RequestTargetHost(), // Recommended protocol interceptors new RequestUserAgent(), new RequestExpectContinue() }); _httpexecutor = new HttpRequestExecutor(); _httpcontext = new BasicHttpContext(null); _connection = new DefaultHttpClientConnection(); _connectionStrategy = new DefaultConnectionReuseStrategy(); }
/** * Default Http parameters got from the DefaultHttpClient implementation. * * @return * Default HTTP connection parameters */ public static HttpParams createDefaultHttpParams() { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 8192); // determine the release version from packaged version info final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", HttpClient.class.getClassLoader()); final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.5)"); return params; }
/** * Creates the default set of HttpParams by invoking {@link DefaultHttpClient#setDefaultHttpParams(HttpParams)} * * @return a new instance of {@link SyncBasicHttpParams} with the defaults applied to it. */ @Override protected HttpParams createHttpParams() { HttpParams params = new SyncBasicHttpParams(); setDefaultHttpParams(params); return params; }
public RequestListenerThread(int port, final String docroot) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler(docroot)); // Set up the HTTP service this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); IOEventDispatch ioEventDispatch = new DefaultIoEventDispatch(); ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); ioReactor.listen(new InetSocketAddress(8080)); try { 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"); }
/** * Obtains a set of reasonable default parameters for a server. * * @return default parameters */ protected HttpParams newDefaultParams() { HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "LocalTestServer/1.1"); return params; }
/** * Creates the default set of HttpParams by invoking {@link DefaultHttpClient#setDefaultHttpParams(HttpParams)} * * @return a new instance of {@link SyncBasicHttpParams} with the defaults applied to it. */ @Override protected HttpParams createHttpParams() { final HttpParams params = new SyncBasicHttpParams(); setDefaultHttpParams(params); return params; }
public RequestListenerThread(int port, String docRoot) throws IOException { this.docRoot = docRoot; this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor HttpProcessor httpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); this.serversocket.setSoTimeout(3000); }
/** * * @throws Exception . */ private void init() throws IOReactorException { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpConnectionParams.setConnectionTimeout(params, connectionTimeOut); HttpConnectionParams.setSoTimeout(params, 3000); httpclient = new DefaultHttpAsyncClient(params); httpclient.start(); }
/** * * @param isMultiRequest * 是否支持多线程 * @param connectionTimeout * 建立连接超时时间(毫秒) * @param socketTimeout * 等待数据超时时间(毫秒) * @return */ public static HttpClient getHttpClient(boolean isMultiRequest, int connectionTimeout, int socketTimeout) { SchemeRegistry schemeRegistry = SchemeRegistryFactory.createDefault(); ClientConnectionManager cm = isMultiRequest ? new PoolingClientConnectionManager( schemeRegistry) : new BasicClientConnectionManager( schemeRegistry); HttpParams params = isMultiRequest ? new SyncBasicHttpParams() : new BasicHttpParams(); HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, socketTimeout); return new DefaultHttpClient(cm, params); }
public RequestListenerThread(int port) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler()); // Set up the HTTP service this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); 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, params); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { HttpEntity[] requestBodies = { new StringEntity( "This is the first test request", "UTF-8"), new ByteArrayEntity( "This is the second test request".getBytes("UTF-8")), new InputStreamEntity( new ByteArrayInputStream( "This is the third test request (will be chunked)" .getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
public RequestListenerThread(int port, final HttpHost target) throws IOException { this.target = target; this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up HTTP protocol processor for incoming connections HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Set up HTTP protocol processor for outgoing connections HttpProcessor outhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Set up outgoing request executor HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); // Set up incoming request handler HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new ProxyHandler( this.target, outhttpproc, httpexecutor)); // Set up the HTTP service this.httpService = new HttpService( inhttpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1"); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); // We are going to use this object to synchronize between the // I/O event and main threads CountDownLatch requestCount = new CountDownLatch(3); BufferingHttpClientHandler handler = new BufferingHttpClientHandler( httpproc, new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params); handler.setEventListener(new EventLogger()); final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params); Thread t = new Thread(new Runnable() { public void run() { try { 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"); } }); t.start(); SessionRequest[] reqs = new SessionRequest[3]; reqs[0] = ioReactor.connect( new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"), new MySessionRequestCallback(requestCount)); reqs[1] = ioReactor.connect( new InetSocketAddress("www.google.com", 80), null, new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount)); reqs[2] = ioReactor.connect( new InetSocketAddress("www.apache.org", 80), null, new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount)); // Block until all connections signal // completion of the request execution requestCount.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } boolean useFileChannels = true; if (args.length >= 2) { String s = args[1]; if (s.equalsIgnoreCase("disableFileChannels")) { useFileChannels = false; } } HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); final HttpFileHandler filehandler = new HttpFileHandler(args[0], useFileChannels); NHttpRequestHandlerResolver resolver = new NHttpRequestHandlerResolver() { public NHttpRequestHandler lookup(String requestURI) { return filehandler; } }; handler.setHandlerResolver(resolver); // Provide an event logger handler.setEventListener(new EventLogger()); IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params); ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); try { ioReactor.listen(new InetSocketAddress(8080)); 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"); }
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler(args[0])); handler.setHandlerResolver(reqistry); // Provide an event logger handler.setEventListener(new EventLogger()); IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params); ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); try { ioReactor.listen(new InetSocketAddress(8080)); 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"); }
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } ClassLoader cl = NHttpSSLServer.class.getClassLoader(); URL url = cl.getResource("test.keystore"); KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "nopassword".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "nopassword".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Jakarta-HttpComponents-NIO/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler(args[0])); handler.setHandlerResolver(reqistry); // Provide an event logger handler.setEventListener(new EventLogger()); IOEventDispatch ioEventDispatch = new SSLServerIOEventDispatch( handler, sslcontext, params); ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); try { ioReactor.listen(new InetSocketAddress(8080)); 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"); }
public static void sendReport(URL pTarget, String pData) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[]{ // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(pTarget.getHost(), pTarget.getPort()); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { HttpEntity[] requestBodies = { new StringEntity(pData)}; for (HttpEntity requestBody : requestBodies) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", pTarget.getPath() + "?" + pTarget.getQuery()); request.setEntity(requestBody); // System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); // System.out.println("<< Response: " + response.getStatusLine()); // System.out.println(EntityUtils.toString(response.getEntity())); // System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
public static void main(String[] args) throws Exception { HttpHost target = new HttpHost("jakarta.apache.org", 80, "http"); // some general setup // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. SchemeRegistry supportedSchemes = new SchemeRegistry(); supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); // Prepare parameters. // Since this example doesn't use the full core framework, // only few parameters are actually required. HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(params, false); // one operator can be used for many connections ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes); HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1); req.addHeader("Host", target.getHostName()); HttpContext ctx = new BasicHttpContext(); OperatedClientConnection conn = scop.createConnection(); try { System.out.println("opening connection to " + target); scop.openConnection(conn, target, null, ctx, params); System.out.println("sending request"); conn.sendRequestHeader(req); // there is no request entity conn.flush(); System.out.println("receiving response header"); HttpResponse rsp = conn.receiveResponseHeader(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); } finally { System.out.println("closing connection"); conn.close(); } }