Example usage for org.apache.http.conn.routing HttpRoute HttpRoute

List of usage examples for org.apache.http.conn.routing HttpRoute HttpRoute

Introduction

In this page you can find the example usage for org.apache.http.conn.routing HttpRoute HttpRoute.

Prototype

public HttpRoute(final HttpHost target) 

Source Link

Document

Creates a new direct insecure route.

Usage

From source file:com.certivox.net.HTTPConnector.java

public HTTPConnector(String url) throws URISyntaxException {
    super();//from w w  w. j av a  2  s  . c  om
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(MAX_CONNECTIONS);
    cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    cm.setMaxPerRoute(new HttpRoute(HttpRequestFactory.createHost(new URI(url))), MAX_COONECTIONS_FOR_HOST);
    httpClient = HttpClients.custom().setConnectionManager(cm).build();
}

From source file:com.bbxiaoqu.api.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests
 * @param context to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 *///from  ww  w  .  j  a  v a  2  s .c  om
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20000);
    HttpConnectionParams.setSoTimeout(params, 20000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Increase max total connection to 60
    ConnManagerParams.setMaxTotalConnections(params, 60);
    // Increase default max connection per route to 20
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
    // Increase max connections for localhost:80 to 20
    HttpHost localhost = new HttpHost("locahost", 80);
    connPerRoute.setMaxForRoute(new HttpRoute(localhost), 20);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Use a session cache for SSL sockets
    //        SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
    //        SSLCertificateSocketFactory.getDefault (30 * 1000);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}

From source file:com.appassit.http.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /*  ww  w. j  av a  2s.  c  o m*/
 * @param userAgent
 *            to report in your HTTP requests
 * @param context
 *            to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20000);
    HttpConnectionParams.setSoTimeout(params, 20000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Increase max total connection to 60
    ConnManagerParams.setMaxTotalConnections(params, 60);
    // Increase default max connection per route to 20
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
    // Increase max connections for localhost:80 to 20
    HttpHost localhost = new HttpHost("locahost", 80);
    connPerRoute.setMaxForRoute(new HttpRoute(localhost), 20);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Use a session cache for SSL sockets
    // SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
    // SSLCertificateSocketFactory.getDefault (30 * 1000);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}

From source file:org.yamj.core.tools.web.PoolingHttpClient.java

private void setRoute(HttpUriRequest request) throws ClientProtocolException {
    HttpHost httpHost = determineTarget(request);
    String key = httpHost.toString();

    synchronized (routedHosts) {
        if (!routedHosts.contains(key)) {
            String group = ".*";
            for (String searchGroup : groupLimits.keySet()) {
                if (key.matches(searchGroup) && searchGroup.length() > group.length()) {
                    group = searchGroup;

                }//  ww w  .j a v  a2s  . c  o m
            }
            int maxRequests = groupLimits.get(group);

            LOG.debug("IO download host: {}; rule: {}, maxRequests: {}", key, group, maxRequests);
            routedHosts.add(key);

            HttpRoute httpRoute = new HttpRoute(httpHost);

            ClientConnectionManager conMan = this.getConnectionManager();
            if (conMan instanceof PoolingClientConnectionManager) {
                PoolingClientConnectionManager poolMan = (PoolingClientConnectionManager) conMan;
                poolMan.setMaxPerRoute(httpRoute, maxRequests);
            }
        }
    }
}

From source file:gr.wavesoft.webng.io.web.WebStreams.java

public static HttpResponse httpGET(URL url, HashMap<String, String> headers) throws IOException {
    try {//from   w w  w . j a va2  s  . c o  m

        // WebRequest connection
        ClientConnectionRequest connRequest = connectionManager.requestConnection(
                new HttpRoute(new HttpHost(url.getHost(), url.getPort(), url.getProtocol())), null);

        ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);
        try {

            // Prepare request
            BasicHttpRequest request = new BasicHttpRequest("GET", url.getPath());

            // Setup headers
            if (headers != null) {
                for (String k : headers.keySet()) {
                    request.addHeader(k, headers.get(k));
                }
            }

            // Send request
            conn.sendRequestHeader(request);

            // Fetch response
            HttpResponse response = conn.receiveResponseHeader();
            conn.receiveResponseEntity(response);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);
                // Replace entity
                response.setEntity(managedEntity);
            }

            // Do something useful with the response
            // The connection will be released automatically 
            // as soon as the response content has been consumed
            return response;

        } catch (IOException ex) {
            // Abort connection upon an I/O error.
            conn.abortConnection();
            throw ex;
        }

    } catch (HttpException ex) {
        throw new IOException("HTTP Exception occured", ex);
    } catch (InterruptedException ex) {
        throw new IOException("InterruptedException", ex);
    } catch (ConnectionPoolTimeoutException ex) {
        throw new IOException("ConnectionPoolTimeoutException", ex);
    }

}

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/** Constructor
 * @param host Host Name/*from  w w  w. j  a va 2 s  . c o m*/
 * @param port Port Name
 * @param secure
 * @param connectionTimeout
 * @param operationTimeout
 * @param maxConnections
 * @param processQueueSize
 * @param timeToLiveInSecs
 */
protected HttpConnectionPool(final String name, String host, Integer port, Boolean secure,
        Integer connectionTimeout, Integer operationTimeout, Integer maxConnections, Integer processQueueSize,
        Integer timeToLiveInSecs) {
    this.name = name;
    this.host = host;
    this.port = port;
    this.secure = secure;
    this.headers = new HashMap<String, String>();
    this.processQueue = new Semaphore(processQueueSize + maxConnections);
    if (timeToLiveInSecs != null) {
        this.timeToLiveInSecs = timeToLiveInSecs;
    }
    this.requestGzipEnabled = false;
    this.responseGzipEnabled = false;

    // create scheme
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (this.secure) {
        schemeRegistry.register(new Scheme("https", port, SSLSocketFactory.getSocketFactory()));
    } else {
        schemeRegistry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory()));
    }

    // create connection manager
    PoolingClientConnectionManager cm;
    if (this.timeToLiveInSecs > 0) {
        cm = new PoolingClientConnectionManager(schemeRegistry, this.timeToLiveInSecs, TimeUnit.SECONDS);
    } else {
        cm = new PoolingClientConnectionManager(schemeRegistry);
    }

    // Max pool size
    cm.setMaxTotal(maxConnections);

    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(maxConnections);

    // Increase max connections for host:port
    HttpHost httpHost = new HttpHost(host, port);
    cm.setMaxPerRoute(new HttpRoute(httpHost), maxConnections);

    // set timeouts
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, operationTimeout);

    // create client pool
    this.client = new DefaultHttpClient(cm, httpParams);

    // policies (cookie)
    this.client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);

    // adding gzip support for http client
    addGzipHeaderInRequestResponse();

}

From source file:org.artifactory.util.HttpClientConfigurator.java

/**
 * Creates custom Http Client connection pool to be used by Http Client
 *
 * @return {@link PoolingHttpClientConnectionManager}
 *//*from w ww  .ja va  2  s  .  c o m*/
private PoolingHttpClientConnectionManager createConnectionMgr() {
    PoolingHttpClientConnectionManager connectionMgr;
    connectionMgr = new PoolingHttpClientConnectionManager(INACTIVITY_TIMEOUT, TimeUnit.MILLISECONDS);
    connectionMgr.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    connectionMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_HOST);
    HttpHost localhost = new HttpHost(LOCALHOST, DEFAULT_PORT);
    connectionMgr.setMaxPerRoute(new HttpRoute(localhost), DEFAULT_POOL_MAX_CONNECTIONS_PER_ROUTE);
    return connectionMgr;
}

From source file:io.github.thred.climatetray.ClimateTrayProxySettings.java

public CloseableHttpClient createHttpClient(String... additionalProxyExcludes) {
    if (proxyType == ProxyType.NONE) {
        return HttpClients.createDefault();
    }/* ww  w .j a v a2 s . co  m*/

    if (proxyType == ProxyType.SYSTEM_DEFAULT) {
        return HttpClients.createSystem();
    }

    HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
    HttpClientBuilder builder = HttpClientBuilder.create().setProxy(proxy);

    if (isProxyAuthorizationNeeded()) {
        Credentials credentials = new UsernamePasswordCredentials(getProxyUser(), getProxyPassword());
        AuthScope authScope = new AuthScope(getProxyHost(), getProxyPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(authScope, credentials);

        builder.setDefaultCredentialsProvider(credsProvider);
    }

    String excludes = proxyExcludes;

    if (Utils.isBlank(excludes)) {
        excludes = "";
    }

    for (String additionalProxyExclude : additionalProxyExcludes) {
        if (excludes.length() > 0) {
            excludes += ", ";
        }

        excludes += additionalProxyExclude;
    }

    if (!Utils.isBlank(excludes)) {
        WildcardPattern pattern = new WildcardPattern(excludes.split("\\s*,\\s*"));
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {
            @Override
            public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context)
                    throws HttpException {
                InetAddress address = host.getAddress();

                if (address == null) {
                    try {
                        address = InetAddress.getByName(host.getHostName());
                    } catch (UnknownHostException e) {
                        ClimateTray.LOG.info("Failed to determine address of host \"%s\"", host.getHostName());
                    }
                }

                if (address != null) {
                    String hostAddress = address.getHostAddress();

                    if (pattern.matches(hostAddress)) {
                        return new HttpRoute(host);
                    }
                }

                String hostName = host.getHostName();

                if (pattern.matches(hostName)) {
                    return new HttpRoute(host);
                }

                return super.determineRoute(host, request, context);
            }
        };

        builder.setRoutePlanner(routePlanner);
    }

    return builder.build();
}

From source file:org.pentaho.di.trans.ael.websocket.SessionConfigurator.java

private HttpContext getContext(URI uri) {
    HttpClientContext httpClientContext = HttpClientContext.create();
    //used by httpclient version >= 4.3
    httpClientContext.setAttribute(HttpClientContext.HTTP_ROUTE,
            new HttpRoute(new HttpHost(uri.getHost(), uri.getPort())));
    //used by httpclient version 4.2
    httpClientContext.setAttribute(HttpClientContext.HTTP_TARGET_HOST,
            new HttpHost(uri.getHost(), uri.getPort()));
    return httpClientContext;
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnectorTest.java

@Test(expected = IllegalStateException.class)
public void testDispose() throws ConnectionPoolTimeoutException, InterruptedException {
    final DefaultHttpClient client = (DefaultHttpClient) underTest.client();
    underTest.dispose();//from w w  w . ja  v  a  2s .c  o m
    client.getConnectionManager().requestConnection(new HttpRoute(new HttpHost("host")), null)
            .getConnection(1000, TimeUnit.SECONDS);
}