Java 类org.apache.http.protocol.RequestTargetHost 实例源码

项目:lams    文件:ProxyClient.java   
public ProxyClient(final HttpParams params) {
    super();
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    this.httpProcessor = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            new RequestContent(),
            new RequestTargetHost(),
            new RequestClientConnControl(),
            new RequestUserAgent(),
            new RequestProxyAuthentication()
    } );
    this.requestExec = new HttpRequestExecutor();
    this.proxyAuthStrategy = new ProxyAuthenticationStrategy();
    this.authenticator = new HttpAuthenticator();
    this.proxyAuthState = new AuthState();
    this.authSchemeRegistry = new AuthSchemeRegistry();
    this.authSchemeRegistry.register(AuthPolicy.BASIC, new BasicSchemeFactory());
    this.authSchemeRegistry.register(AuthPolicy.DIGEST, new DigestSchemeFactory());
    this.authSchemeRegistry.register(AuthPolicy.NTLM, new NTLMSchemeFactory());
    this.authSchemeRegistry.register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());
    this.authSchemeRegistry.register(AuthPolicy.KERBEROS, new KerberosSchemeFactory());
    this.reuseStrategy = new DefaultConnectionReuseStrategy();
    this.params = params;
}
项目:lams    文件:DefaultHttpClient.java   
/**
* Create the processor with the following interceptors:
* <ul>
* <li>{@link RequestDefaultHeaders}</li>
* <li>{@link RequestContent}</li>
* <li>{@link RequestTargetHost}</li>
* <li>{@link RequestClientConnControl}</li>
* <li>{@link RequestUserAgent}</li>
* <li>{@link RequestExpectContinue}</li>
* <li>{@link RequestAddCookies}</li>
* <li>{@link ResponseProcessCookies}</li>
* <li>{@link RequestAuthCache}</li>
* <li>{@link RequestTargetAuthentication}</li>
* <li>{@link RequestProxyAuthentication}</li>
* </ul>
* <p>
* @return the processor with the added interceptors.
*/
@Override
protected BasicHttpProcessor createHttpProcessor() {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestDefaultHeaders());
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestClientConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    // HTTP state management interceptors
    httpproc.addInterceptor(new RequestAddCookies());
    httpproc.addInterceptor(new ResponseProcessCookies());
    // HTTP authentication interceptors
    httpproc.addInterceptor(new RequestAuthCache());
    httpproc.addInterceptor(new RequestTargetAuthentication());
    httpproc.addInterceptor(new RequestProxyAuthentication());
    return httpproc;
}
项目:megabasterd    文件:MiscTools.java   
private static HttpClientBuilder _getApacheKissHttpClientBuilder() {

        return HttpClients.custom()
                .addInterceptorFirst(new RequestDefaultHeaders())
                .addInterceptorFirst(new RequestContent())
                .addInterceptorFirst(new RequestTargetHost())
                .addInterceptorFirst(new RequestClientConnControl())
                .addInterceptorFirst(new RequestAddCookies())
                .addInterceptorFirst(new ResponseProcessCookies())
                .addInterceptorFirst(new RequestAuthCache())
                .addInterceptorLast(new HttpRequestInterceptor() {

                    @Override
                    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

                        if (request.containsHeader("User-Agent")) {

                            request.removeHeaders("User-Agent");

                        }

                        if (request.containsHeader("Custom-User-Agent")) {

                            request.addHeader("User-Agent", request.getFirstHeader("Custom-User-Agent").getValue());

                            request.removeHeaders("Custom-User-Agent");
                        }
                    }

                });
    }
项目:purecloud-iot    文件:DefaultHttpClient.java   
/**
* Create the processor with the following interceptors:
* <ul>
* <li>{@link RequestDefaultHeaders}</li>
* <li>{@link RequestContent}</li>
* <li>{@link RequestTargetHost}</li>
* <li>{@link RequestClientConnControl}</li>
* <li>{@link RequestUserAgent}</li>
* <li>{@link RequestExpectContinue}</li>
* <li>{@link RequestAddCookies}</li>
* <li>{@link ResponseProcessCookies}</li>
* <li>{@link RequestAuthCache}</li>
* <li>{@link RequestTargetAuthentication}</li>
* <li>{@link RequestProxyAuthentication}</li>
* </ul>
* <p>
* @return the processor with the added interceptors.
*/
@Override
protected BasicHttpProcessor createHttpProcessor() {
    final BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestDefaultHeaders());
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestClientConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    // HTTP state management interceptors
    httpproc.addInterceptor(new RequestAddCookies());
    httpproc.addInterceptor(new ResponseProcessCookies());
    // HTTP authentication interceptors
    httpproc.addInterceptor(new RequestAuthCache());
    httpproc.addInterceptor(new RequestTargetAuthentication());
    httpproc.addInterceptor(new RequestProxyAuthentication());
    return httpproc;
}
项目:purecloud-iot    文件:MinimalClientExec.java   
public MinimalClientExec(
        final HttpRequestExecutor requestExecutor,
        final HttpClientConnectionManager connManager,
        final ConnectionReuseStrategy reuseStrategy,
        final ConnectionKeepAliveStrategy keepAliveStrategy) {
    Args.notNull(requestExecutor, "HTTP request executor");
    Args.notNull(connManager, "Client connection manager");
    Args.notNull(reuseStrategy, "Connection reuse strategy");
    Args.notNull(keepAliveStrategy, "Connection keep alive strategy");
    this.httpProcessor = new ImmutableHttpProcessor(
            new RequestContent(),
            new RequestTargetHost(),
            new RequestClientConnControl(),
            new RequestUserAgent(VersionInfo.getUserAgent(
                    "Apache-HttpClient", "org.apache.http.client", getClass())));
    this.requestExecutor    = requestExecutor;
    this.connManager        = connManager;
    this.reuseStrategy      = reuseStrategy;
    this.keepAliveStrategy  = keepAliveStrategy;
}
项目:purecloud-iot    文件:ProxyClient.java   
/**
 * @since 4.3
 */
public ProxyClient(
        final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
        final ConnectionConfig connectionConfig,
        final RequestConfig requestConfig) {
    super();
    this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE;
    this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT;
    this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT;
    this.httpProcessor = new ImmutableHttpProcessor(
            new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent());
    this.requestExec = new HttpRequestExecutor();
    this.proxyAuthStrategy = new ProxyAuthenticationStrategy();
    this.authenticator = new HttpAuthenticator();
    this.proxyAuthState = new AuthState();
    this.authSchemeRegistry = new AuthSchemeRegistry();
    this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactory());
    this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory());
    this.authSchemeRegistry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory());
    this.authSchemeRegistry.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory());
    this.reuseStrategy = new DefaultConnectionReuseStrategy();
}
项目:cJUnit-mc626    文件:DefaultHttpClient.java   
@Override
protected BasicHttpProcessor createHttpProcessor() {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestDefaultHeaders());
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestClientConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    // HTTP state management interceptors
    httpproc.addInterceptor(new RequestAddCookies());
    httpproc.addInterceptor(new ResponseProcessCookies());
    // HTTP authentication interceptors
    httpproc.addInterceptor(new RequestTargetAuthentication());
    httpproc.addInterceptor(new RequestProxyAuthentication());
    return httpproc;
}
项目:contrail-java-api    文件:ApiConnectorImpl.java   
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();
}
项目:java-binrepo-proxy    文件:ElementalReverseProxy.java   
public RequestListenerThread(final int port, final HttpHost target) throws IOException {
    this.target = target;
    this.serversocket = new ServerSocket(port);

    // Set up HTTP protocol processor for incoming connections
    final HttpProcessor inhttpproc = new ImmutableHttpProcessor(
            new HttpRequestInterceptor[] {
                    new RequestContent(),
                    new RequestTargetHost(),
                    new RequestConnControl(),
                    new RequestUserAgent("Test/1.1"),
                    new RequestExpectContinue(true)
     });

    // Set up HTTP protocol processor for outgoing connections
    final HttpProcessor outhttpproc = new ImmutableHttpProcessor(
            new HttpResponseInterceptor[] {
                    new ResponseDate(),
                    new ResponseServer("Test/1.1"),
                    new ResponseContent(),
                    new ResponseConnControl()
    });

    // Set up outgoing request executor
    final HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    // Set up incoming request handler
    final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new ProxyHandler(
            this.target,
            outhttpproc,
            httpexecutor));

    // Set up the HTTP service
    this.httpService = new HttpService(inhttpproc, reqistry);
}
项目:java-binrepo-proxy    文件:HttpCoreTransportServer.java   
public RequestListenerThread(final int port, final HttpHost target, final TransportHandler handler) throws IOException {
    this.target = target;
    this.serversocket = new ServerSocket(port);

    // Set up HTTP protocol processor for incoming connections
    final HttpProcessor inhttpproc = new ImmutableHttpProcessor(
            new HttpRequestInterceptor[] {
                    new RequestContent(),
                    new RequestTargetHost(),
                    new RequestConnControl(),
                    new RequestUserAgent("Test/1.1"),
                    new RequestExpectContinue(true)
     });

    // Set up HTTP protocol processor for outgoing connections
    final HttpProcessor outhttpproc = new ImmutableHttpProcessor(
            new HttpResponseInterceptor[] {
                    new ResponseDate(),
                    new ResponseServer("Test/1.1"),
                    new ResponseContent(),
                    new ResponseConnControl()
    });

    // Set up outgoing request executor
    final HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    // Set up incoming request handler
    final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new ProxyHandler(
            this.target,
            outhttpproc,
            httpexecutor,
            handler));

    // Set up the HTTP service
    this.httpService = new HttpService(inhttpproc, reqistry);
}
项目:java-binrepo-proxy    文件:HttpCoreTransportClientImpl.java   
@Override
public TransportFetch httpGetOtherFile(String uri) {
    HttpProcessor httpproc = HttpProcessorBuilder.create()
    .add(new RequestContent())
    .add(new RequestTargetHost())
    .add(new RequestConnControl())
    .add(new RequestUserAgent("Test/1.1"))
    .add(new RequestExpectContinue(true)).build();

    try {
        HttpRequest ascRequest = new BasicHttpRequest("GET", uri);
        LOG.info("Will fetch {}", ascRequest.getRequestLine());
        httpexecutor.preProcess(ascRequest, httpproc, context);
        final HttpResponse otherResponse = httpexecutor.execute(ascRequest, conn, context);
        httpexecutor.postProcess(response, httpproc, context);

        final byte[] otherBody = EntityUtils.toByteArray(otherResponse.getEntity());
        LOG.info("Read body of {} bytes", otherBody.length, " bytes");
        EntityUtils.consume(otherResponse.getEntity());

        boolean keepalive = connStrategy.keepAlive(response, context);
        context.setAttribute(HTTP_CONN_KEEPALIVE, new Boolean(keepalive));

        return new TransportFetch(otherResponse.getStatusLine().getStatusCode(), otherResponse.getStatusLine().getReasonPhrase(), otherBody);
    } catch (HttpException | IOException ex) {
        return new TransportFetch(500, ex.getLocalizedMessage(), null);
    }
}
项目:purecloud-iot    文件:MainClientExec.java   
public MainClientExec(
        final HttpRequestExecutor requestExecutor,
        final HttpClientConnectionManager connManager,
        final ConnectionReuseStrategy reuseStrategy,
        final ConnectionKeepAliveStrategy keepAliveStrategy,
        final AuthenticationStrategy targetAuthStrategy,
        final AuthenticationStrategy proxyAuthStrategy,
        final UserTokenHandler userTokenHandler) {
    this(requestExecutor, connManager, reuseStrategy, keepAliveStrategy,
            new ImmutableHttpProcessor(new RequestTargetHost()),
            targetAuthStrategy, proxyAuthStrategy, userTokenHandler);
}
项目:jsonrpc4j    文件:JsonRpcHttpAsyncClient.java   
private void initialize() {
    if (initialized.getAndSet(true)) {
        return;
    }
    IOReactorConfig.Builder config = createConfig();
    // params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0");
    final ConnectingIOReactor ioReactor = createIoReactor(config);
    createSslContext();
    int socketBufferSize = Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024);
    final ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(socketBufferSize).build();
    BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, connectionConfig);
    pool = new BasicNIOConnPool(ioReactor, nioConnFactory, Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000));
    pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500));
    pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500));

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
                IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext, connectionConfig);
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
        }
    }, "jsonrpc4j HTTP IOReactor");

    t.setDaemon(true);
    t.start();

    HttpProcessor httpProcessor = new ImmutableHttpProcessor(new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(false));
    requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy());
}
项目:PhET    文件:ElementalHttpGet.java   
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();
    }
}
项目:PhET    文件:ElementalHttpPost.java   
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();
    }        
}
项目:PhET    文件:ElementalReverseProxy.java   
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);
}
项目:PhET    文件:NHttpClient.java   
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");
}
项目:Jouve-Project    文件:ConnectorManagerRequestUtils.java   
public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) {
        try {
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
            HttpProtocolParams.setUseExpectContinue(params, true);

            BasicHttpProcessor httpproc = new BasicHttpProcessor();
            // Required protocol interceptors
            httpproc.addInterceptor(new RequestContent());
            httpproc.addInterceptor(new RequestTargetHost());
            // Recommended protocol interceptors
            httpproc.addInterceptor(new RequestConnControl());
            httpproc.addInterceptor(new RequestUserAgent());
            httpproc.addInterceptor(new RequestExpectContinue());

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

            HttpContext context = new BasicHttpContext(null);

            URL connectorManagerURL = new URL(connectorManager.getUrl());
            HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
            ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

            try {
                HttpEntity requestBody;
                if (document != null) {
//                  OutputFormat format = OutputFormat.createPrettyPrint();
                    OutputFormat format = OutputFormat.createCompactFormat();
                    StringWriter stringWriter = new StringWriter();
                    XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
                    xmlWriter.write(document);
                    String xmlAsString = stringWriter.toString();
                    requestBody = new StringEntity(xmlAsString, "UTF-8");
                } else {
                    requestBody = null;
                }
                if (!conn.isOpen()) {
                    Socket socket = new Socket(host.getHostName(), host.getPort());
                    conn.bind(socket, params);
                }

                String target = connectorManager.getUrl() + servletPath;

                BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target);
                request.setEntity(requestBody);
                LOGGER.info(">> 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);

                LOGGER.info("<< Response: " + response.getStatusLine());
                String entityText = EntityUtils.toString(response.getEntity());
                LOGGER.info(entityText);
                LOGGER.info("==============");
                if (!connStrategy.keepAlive(response, context)) {
                    conn.close();
                } else {
                    LOGGER.info("Connection kept alive...");
                }

                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } finally {
                conn.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }