Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager.

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:net.ecfirm.ec.ec1.net.EcNetHelper.java

public static DefaultHttpClient getThreadSafeClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    //////////from  w ww .ja v  a  2 s. com
    client.getParams().setParameter("http.protocol.expect-continue", false);
    client.getParams().setParameter("http.connection.timeout", EcConst.NET_HTTP_CONN_TIMEOUT);
    //client.getParams().setParameter("http.socket.timeout", );
    ////////
    HttpParams params = client.getParams();
    ////////
    ConnManagerParams.setMaxTotalConnections(params, EcConst.NET_HTTP_CONN);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(EcConst.NET_HTTP_CONN_PER_ROUTE);
    HttpHost localhost = new HttpHost("localhost", 80);
    connPerRoute.setMaxForRoute(new HttpRoute(localhost), EcConst.NET_HTTP_CONN_PER_ROUTE);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    mgr.getSchemeRegistry().register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    mgr.getSchemeRegistry().register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ////////
    client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
    return client;
}

From source file:org.transitime.avl.amigocloud.AmigoRest.java

/********************** Member Functions **************************/

private static DefaultHttpClient getThreadSafeClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    HttpParams params = client.getParams();
    client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
    return client;
}

From source file:jsonclient.JsonClient.java

public static String setSlide(String message) throws IOException {
    String url = "http://something";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    String response = postToURL(url, message, httpClient);
    httpClient.getConnectionManager().shutdown();
    return response;
}

From source file:com.google.resting.rest.client.impl.RESTClient.java

/**
 * Executes secure SSL request using HTTPS
 * /*from w w w  .  j  a v  a 2s  .c o m*/
 * @param Domain of the REST endpoint
 * @param path Path of the URI
 * @param port port number of the REST endpoint
 * @param verb Type of HTTP method(GET/POST/PUT/DELETE)
 * 
 * @return ServiceResponse object containing http status code and entire response as a String
 */
public static ServiceResponse secureInvoke(ServiceContext serviceContext) {
    String targetDomain = serviceContext.getTargetDomain();
    int port = serviceContext.getPort();
    ServiceResponse serviceResponse = null;
    EncodingTypes charset = serviceContext.getCharset();
    try {
        long ioStartTime = System.currentTimeMillis();
        HttpHost targetHost = new HttpHost(targetDomain, port, RequestConstants.HTTPS);
        HttpRequest request = buildHttpRequest(serviceContext);

        DefaultHttpClient httpclient = buildHttpClient(serviceContext);
        httpclient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme(RequestConstants.HTTPS, new CustomSSLSocketFactory(), port));

        HttpResponse response = httpclient.execute(targetHost, request);
        serviceResponse = new ServiceResponse(response, charset);
        long ioEndTime = System.currentTimeMillis();

        System.out.println("Time taken in executing REST: " + (ioEndTime - ioStartTime));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return serviceResponse;

}

From source file:org.jboss.as.test.integration.management.interfaces.HttpManagementInterface.java

private static HttpClient createHttpClient(String host, int port, String username, String password) {
    PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool);
    SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    try {/*from  ww w .  jav a 2s  .  c om*/
        schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, new AllowAllHostnameVerifier())));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true));
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST),
            new UsernamePasswordCredentials(username, password));

    return httpClient;
}

From source file:de.onyxbits.raccoon.gplay.PlayManager.java

/**
 * create a proxy client//ww w. j  a  v a2s  .  c om
 * 
 * @return either a client or null if none is configured
 * @throws KeyManagementException
 * @throws NumberFormatException
 *           if that port could not be parsed.
 * @throws NoSuchAlgorithmException
 */
private static HttpClient createProxyClient(PlayProfile profile)
        throws KeyManagementException, NoSuchAlgorithmException {
    if (profile.getProxyAddress() == null) {
        return null;
    }

    PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(30);

    DefaultHttpClient client = new DefaultHttpClient(connManager);
    client.getConnectionManager().getSchemeRegistry().register(Utils.getMockedScheme());
    HttpHost proxy = new HttpHost(profile.getProxyAddress(), profile.getProxyPort());
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (profile.getProxyUser() != null && profile.getProxyPassword() != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(proxy),
                new UsernamePasswordCredentials(profile.getProxyUser(), profile.getProxyPassword()));
    }
    return client;
}

From source file:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ///*from  w w  w  .j a v a 2  s  .  c  o m*/
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:org.lorislab.armonitor.util.RestClient.java

/**
 * Gets the rest-service client./*  w w  w .  j  a  v a2 s  .co  m*/
 *
 * @param <T> the rest-service client implementation.
 * @param clazz the rest-service class.
 * @param url the server URL.
 * @param username the username.
 * @param password the password.
 * @param auth the authentication flag.
 * @exception Exception if the method fails.
 *
 * @return the the rest-service client instance.
 */
public static <T> T getClient(final Class<T> clazz, String url, boolean auth, String username, char[] password)
        throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (url.startsWith(HTTPS)) {
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme(HTTPS, 443, sslSocketFactory));
    }

    if (auth) {
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(username, new String(password));
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClient.setCredentialsProvider(provider);
    }
    return ProxyFactory.create(clazz, url, new ApacheHttpClient4Executor(httpClient));
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static HttpClient newHttpClient() {
    int timeout = 3 * 60 * 1000;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ClientConnectionManager mgr = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry());
    httpClient = new DefaultHttpClient(cm, params);

    // how long are we prepared to wait to establish a connection?
    HttpConnectionParams.setConnectionTimeout(params, timeout);

    // how long should the socket wait for data?
    HttpConnectionParams.setSoTimeout(params, timeout);

    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false) {

        @Override/*from  w  w w  .j  a va2 s .c  o  m*/
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return super.retryRequest(exception, executionCount, context);
        }

        @Override
        public boolean isRequestSentRetryEnabled() {
            return false;
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }

    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            response.removeHeaders("Set-Cookie");

            HttpEntity entity = response.getEntity();
            Header contentEncodingHeader = entity.getContentEncoding();
            if (contentEncodingHeader != null) {
                HeaderElement[] codecs = contentEncodingHeader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }

        }

    });
    return httpClient;
}

From source file:com.waku.common.http.MyHttpClient.java

public static Document getAsDom4jDoc(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());
    try {/*w  ww.ja  v  a 2 s  .  c  om*/
        HttpGet httpGet = new HttpGet(url);
        return getResponseAndConvertToDom(httpclient, httpGet);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}