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

项目: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);
    }
}
项目: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");
}
项目:purecloud-iot    文件:TestConnectionManagement.java   
/**
 * Tests releasing connection from #abort method called from the
 * main execution thread while there is no blocking I/O operation.
 */
@Test
public void testReleaseConnectionOnAbort() throws Exception {

    this.connManager.setMaxTotal(1);

    final HttpHost target = start();
    final HttpRoute route = new HttpRoute(target, null, false);
    final int      rsplen = 8;
    final String      uri = "/random/" + rsplen;
    final HttpContext context = new BasicHttpContext();

    final HttpRequest request =
        new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);

    HttpClientConnection conn = getConnection(this.connManager, route);
    this.connManager.connect(conn, route, 0, context);
    this.connManager.routeComplete(conn, route, context);

    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);

    final HttpProcessor httpProcessor = new ImmutableHttpProcessor(
            new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() });

    final HttpRequestExecutor exec = new HttpRequestExecutor();
    exec.preProcess(request, httpProcessor, context);
    final HttpResponse response = exec.execute(request, conn, context);

    Assert.assertEquals("wrong status in first response",
                 HttpStatus.SC_OK,
                 response.getStatusLine().getStatusCode());

    // check that there are no connections available
    try {
        // this should fail quickly, connection has not been released
        getConnection(this.connManager, route, 100L, TimeUnit.MILLISECONDS);
        Assert.fail("ConnectionPoolTimeoutException should have been thrown");
    } catch (final ConnectionPoolTimeoutException e) {
        // expected
    }

    // abort the connection
    Assert.assertTrue(conn instanceof HttpClientConnection);
    conn.shutdown();
    this.connManager.releaseConnection(conn, null, -1, null);

    // the connection is expected to be released back to the manager
    conn = getConnection(this.connManager, route, 5L, TimeUnit.SECONDS);
    Assert.assertFalse("connection should have been closed", conn.isOpen());

    this.connManager.releaseConnection(conn, null, -1, null);
    this.connManager.shutdown();
}
项目: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);
        }
    }