Package org.apache.http

Examples of org.apache.http.HttpClientConnection


        final HttpRoute route = new HttpRoute(target);

        Mockito.when(connFactory.create(Mockito.<ConnectionConfig>any())).thenReturn(conn);

        final ConnectionRequest connRequest1 = mgr.requestConnection(route, null);
        final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS);
        Assert.assertNotNull(conn1);
        mgr.releaseConnection(conn1, null, 100, TimeUnit.MILLISECONDS);

        mgr.getConnection(route, null);
        mgr.getConnection(route, null);
View Full Code Here


       
        Scheme http = (Scheme) beanfactory.getBean("http-scheme");
        HttpHost host = new HttpHost("www.yahoo.com", 80, http);

        HttpRequestFactory requestfactory = (HttpRequestFactory) beanfactory.getBean("http-request-factory");
        HttpClientConnection conn = (HttpClientConnection) beanfactory.getBean("http-connection");
        ConnectionReuseStrategy connStrategy = (ConnectionReuseStrategy) beanfactory.getBean("conn-reuse-strategy");
        conn.setTargetHost(host);
        try {
            HttpRequest request1 = requestfactory.newHttpRequest("GET", "/");
            HttpResponse response1 = httpexec.execute(request1, conn);
            System.out.println("<< Response: " + response1.getStatusLine());
            System.out.println(EntityUtils.toString(response1.getEntity()));
            System.out.println("==============");
            if (connStrategy.keepAlive(response1)) {
                System.out.println("Connection kept alive...");
            } else {
                conn.close();
                System.out.println("Connection closed...");
            }
            HttpRequest request2 = requestfactory.newHttpRequest("GET", "/stuff");
            HttpResponse response2 = httpexec.execute(request2, conn);
            System.out.println("<< Response: " + response2.getStatusLine());
            System.out.println(EntityUtils.toString(response2.getEntity()));
            System.out.println("==============");
            if (connStrategy.keepAlive(response2)) {
                System.out.println("Connection kept alive...");
            } else {
                conn.close();
                System.out.println("Connection closed...");
            }
        } finally {
            conn.close();
        }
    }
View Full Code Here

        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {
           
            HttpClientConnection conn = (HttpClientConnection) context.getAttribute(
                    HTTP_OUT_CONN);

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.target);
View Full Code Here

        HttpPost request = new HttpPost("/echo/");
        request.setHeader("Host", target.getHostName());
        request.setEntity(new StringEntity(message, charset));

        HttpClientConnection conn = connectTo(target);

        httpContext.setAttribute(
                HttpExecutionContext.HTTP_CONNECTION, conn);
        httpContext.setAttribute(
                HttpExecutionContext.HTTP_TARGET_HOST, target);
        httpContext.setAttribute(
                HttpExecutionContext.HTTP_REQUEST, request);

        HttpParamsLinker.link(request, defaultParams);
        httpExecutor.preProcess
            (request, httpProcessor, httpContext);
        HttpResponse response = httpExecutor.execute
            (request, conn, httpContext);
        HttpParamsLinker.link(response, defaultParams);
        httpExecutor.postProcess
            (response, httpProcessor, httpContext);

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

        String received = EntityUtils.toString(response.getEntity());
        conn.close();

        assertEquals("wrong echo", message, received);
    }
View Full Code Here

            if (sizes[i] < 0)
                uri += "/";

            HttpGet request = new HttpGet(uri);

            HttpClientConnection conn = connectTo(target);
           
            httpContext.setAttribute(
                    HttpExecutionContext.HTTP_CONNECTION, conn);
            httpContext.setAttribute(
                    HttpExecutionContext.HTTP_TARGET_HOST, target);
            httpContext.setAttribute(
                    HttpExecutionContext.HTTP_REQUEST, request);

            HttpParamsLinker.link(request, defaultParams);
            httpExecutor.preProcess
                (request, httpProcessor, httpContext);
            HttpResponse response = httpExecutor.execute
                (request, conn, httpContext);
            HttpParamsLinker.link(response, defaultParams);
            httpExecutor.postProcess
                (response, httpProcessor, httpContext);

            assertEquals("(" + sizes[i] + ") wrong status in response",
                         HttpStatus.SC_OK,
                         response.getStatusLine().getStatusCode());

            byte[] data = EntityUtils.toByteArray(response.getEntity());
            if (sizes[i] >= 0)
                assertEquals("(" + sizes[i] + ") wrong length of response",
                             sizes[i], data.length);
            conn.close();
        }
    }
View Full Code Here

        httpexecutor.addInterceptor(new RequestConnControl());
        httpexecutor.addInterceptor(new RequestUserAgent());
        httpexecutor.addInterceptor(new RequestExpectContinue());
       
        HttpHost host = new HttpHost("localhost", 8080);
        HttpClientConnection conn = new DefaultHttpClientConnection(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)
            };
           
            ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
           
            for (int i = 0; i < requestBodies.length; i++) {
                HttpPost request = new HttpPost("/servlets-examples/servlet/RequestInfoExample");
                request.setEntity(requestBodies[i]);
                System.out.println(">> Request URI: " + request.getRequestLine().getUri());
                HttpResponse response = httpexecutor.execute(request, conn);
                System.out.println("<< Response: " + response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
                System.out.println("==============");
                if (!connStrategy.keepAlive(response)) {
                    conn.close();
                } else {
                    System.out.println("Connection kept alive...");
                }
            }
        } finally {
            conn.close();
        }       
    }
View Full Code Here

        httpexecutor.addInterceptor(new RequestConnControl());
        httpexecutor.addInterceptor(new RequestUserAgent());
        httpexecutor.addInterceptor(new RequestExpectContinue());
       
        HttpHost host = new HttpHost("localhost", 8080);
        HttpClientConnection conn = new DefaultHttpClientConnection(host);
        try {
           
            String[] targets = {
                    "/",
                    "/servlets-examples/servlet/RequestInfoExample",
                    "/somewhere%20in%20pampa"};
           
            ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
           
            for (int i = 0; i < targets.length; i++) {
                HttpGet request = new HttpGet(targets[i]);
                System.out.println(">> Request URI: " + request.getRequestLine().getUri());
                HttpResponse response = httpexecutor.execute(request, conn);
                System.out.println("<< Response: " + response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
                System.out.println("==============");
                if (!connStrategy.keepAlive(response)) {
                    conn.close();
                } else {
                    System.out.println("Connection kept alive...");
                }
            }
        } finally {
            conn.close();
        }
    }
View Full Code Here

            }
        }

        final RequestConfig config = context.getRequestConfig();

        final HttpClientConnection managedConn;
        try {
            final int timeout = config.getConnectionRequestTimeout();
            managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS);
        } catch(final InterruptedException interrupted) {
            Thread.currentThread().interrupt();
            throw new RequestAbortedException("Request aborted", interrupted);
        } catch(final ExecutionException ex) {
            Throwable cause = ex.getCause();
            if (cause == null) {
                cause = ex;
            }
            throw new RequestAbortedException("Request execution failed", cause);
        }

        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);

        if (config.isStaleConnectionCheckEnabled()) {
            // validate connection
            if (managedConn.isOpen()) {
                this.log.debug("Stale connection check");
                if (managedConn.isStale()) {
                    this.log.debug("Stale connection detected");
                    managedConn.close();
                }
            }
        }

        final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn);
        try {
            if (execAware != null) {
                execAware.setCancellable(connHolder);
            }

            HttpResponse response;
            for (int execCount = 1;; execCount++) {

                if (execCount > 1 && !RequestEntityProxy.isRepeatable(request)) {
                    throw new NonRepeatableRequestException("Cannot retry request " +
                            "with a non-repeatable request entity.");
                }

                if (execAware != null && execAware.isAborted()) {
                    throw new RequestAbortedException("Request aborted");
                }

                if (!managedConn.isOpen()) {
                    this.log.debug("Opening connection " + route);
                    try {
                        establishRoute(proxyAuthState, managedConn, route, request, context);
                    } catch (final TunnelRefusedException ex) {
                        if (this.log.isDebugEnabled()) {
                            this.log.debug(ex.getMessage());
                        }
                        response = ex.getResponse();
                        break;
                    }
                }
                final int timeout = config.getSocketTimeout();
                if (timeout >= 0) {
                    managedConn.setSocketTimeout(timeout);
                }

                if (execAware != null && execAware.isAborted()) {
                    throw new RequestAbortedException("Request aborted");
                }

                if (this.log.isDebugEnabled()) {
                    this.log.debug("Executing request " + request.getRequestLine());
                }

                if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Target auth state: " + targetAuthState.getState());
                    }
                    this.authenticator.generateAuthResponse(request, targetAuthState, context);
                }
                if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Proxy auth state: " + proxyAuthState.getState());
                    }
                    this.authenticator.generateAuthResponse(request, proxyAuthState, context);
                }

                response = requestExecutor.execute(request, managedConn, context);

                // The connection is in or can be brought to a re-usable state.
                if (reuseStrategy.keepAlive(response, context)) {
                    // Set the idle duration of this connection
                    final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                    if (this.log.isDebugEnabled()) {
                        final String s;
                        if (duration > 0) {
                            s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                        } else {
                            s = "indefinitely";
                        }
                        this.log.debug("Connection can be kept alive " + s);
                    }
                    connHolder.setValidFor(duration, TimeUnit.MILLISECONDS);
                    connHolder.markReusable();
                } else {
                    connHolder.markNonReusable();
                }

                if (needAuthentication(
                        targetAuthState, proxyAuthState, route, response, context)) {
                    // Make sure the response body is fully consumed, if present
                    final HttpEntity entity = response.getEntity();
                    if (connHolder.isReusable()) {
                        EntityUtils.consume(entity);
                    } else {
                        managedConn.close();
                        if (proxyAuthState.getState() == AuthProtocolState.SUCCESS
                                && proxyAuthState.getAuthScheme() != null
                                && proxyAuthState.getAuthScheme().isConnectionBased()) {
                            this.log.debug("Resetting proxy auth state");
                            proxyAuthState.reset();
View Full Code Here

        final String      uri = "/random/" + rsplen;

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

        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);
        HttpResponse response = exec.execute(request, conn, context);

        Assert.assertEquals("wrong status in first response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        byte[] data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of first response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        // check that there is no auto-release by default
        try {
            // this should fail quickly, connection has not been released
            getConnection(this.connManager, route, 10L, TimeUnit.MILLISECONDS);
            Assert.fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (final ConnectionPoolTimeoutException e) {
            // expected
        }

        conn.close();
        this.connManager.releaseConnection(conn, null, -1, null);
        conn = getConnection(this.connManager, route);
        Assert.assertFalse("connection should have been closed", conn.isOpen());

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

        // repeat the communication, no need to prepare the request again
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
        response = exec.execute(request, conn, context);

        Assert.assertEquals("wrong status in second response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of second response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        // release connection after marking it for re-use
        // expect the next connection obtained to be open
        this.connManager.releaseConnection(conn, null, -1, null);
        conn = getConnection(this.connManager, route);
        Assert.assertTrue("connection should have been open", conn.isOpen());

        // repeat the communication, no need to prepare the request again
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
        response = exec.execute(request, conn, context);
View Full Code Here

        final String      uri = "/random/" + rsplen;

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

        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);
        HttpResponse response = exec.execute(request, conn, context);

        Assert.assertEquals("wrong status in first response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        byte[] data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of first response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        // check that there is no auto-release by default
        try {
            // this should fail quickly, connection has not been released
            getConnection(this.connManager, route, 10L, TimeUnit.MILLISECONDS);
            Assert.fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (final ConnectionPoolTimeoutException e) {
            // expected
        }

        conn.close();
        this.connManager.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
        conn = getConnection(this.connManager, route);
        Assert.assertFalse("connection should have been closed", conn.isOpen());

        // repeat the communication, no need to prepare the request again
        this.connManager.connect(conn, route, 0, context);
        this.connManager.routeComplete(conn, route, context);

        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
        response = exec.execute(request, conn, context);

        Assert.assertEquals("wrong status in second response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of second response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        this.connManager.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
        conn = getConnection(this.connManager, route);
        Assert.assertTrue("connection should have been open", conn.isOpen());

        // repeat the communication, no need to prepare the request again
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
        response = exec.execute(request, conn, context);

        Assert.assertEquals("wrong status in third response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of third response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        this.connManager.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
        Thread.sleep(150);
        conn = getConnection(this.connManager, route);
        Assert.assertTrue("connection should have been closed", !conn.isOpen());

        // repeat the communication, no need to prepare the request again
        this.connManager.connect(conn, route, 0, context);
        this.connManager.routeComplete(conn, route, context);
View Full Code Here

TOP

Related Classes of org.apache.http.HttpClientConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.