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:org.codegist.crest.HttpClientRestService.java

public static RestService newRestService(int maxConcurrentConnection, int maxConnectionPerRoute) {
    DefaultHttpClient httpClient;
    if (maxConcurrentConnection > 1 || maxConnectionPerRoute > 1) {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        if (maxConnectionPerRoute > 1) {
            ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(maxConnectionPerRoute));
        }/*w ww  . j a va  2  s.c  o m*/
        if (maxConcurrentConnection > 1) {
            ConnManagerParams.setMaxTotalConnections(params, maxConcurrentConnection);
        } else {
            ConnManagerParams.setMaxTotalConnections(params, 1);
        }

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpClient = new DefaultHttpClient(cm, params);
    } else {
        httpClient = new DefaultHttpClient();
    }
    httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    return new HttpClientRestService(httpClient);
}

From source file:org.xwiki.extension.repository.xwiki.internal.httpclient.DefaultHttpClientFactory.java

@Override
public HttpClient createClient(String user, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, this.configuration.getUserAgent());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    // Setup proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Setup authentication
    if (user != null) {
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
    }/*  www . j  av  a 2  s.c o  m*/

    return httpClient;
}

From source file:com.axelor.apps.account.ebics.client.HttpRequestSender.java

private DefaultHttpClient getSecuredHttpClient(Certificate cert) throws AxelorException {

    DefaultHttpClient client = new DefaultHttpClient();

    try {//from ww w  . j a v  a  2s . c o m
        KeyStore keystore = KeyStore.getInstance("jks");
        char[] password = "NoPassword".toCharArray();
        keystore.load(null, password);
        keystore.setCertificateEntry("certficate.host", cert);
        Scheme https = new Scheme("https", 443, new SSLSocketFactory(keystore));
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AxelorException(I18n.get("Error adding certificate"), IException.TECHNICAL);
    }

    return client;
}

From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ??URI???./*from w  w w.j  a  va2 s  . c  o m*/
 * 
 * @param uri ????URI
 * @return 
 */
public static byte[] getBytes(final String uri) {
    HttpGet request = new HttpGet(uri);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        byte[] result = httpClient.execute(request, new ResponseHandler<byte[]>() {
            @Override
            public byte[] handleResponse(final HttpResponse response) throws IOException {
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    return EntityUtils.toByteArray(response.getEntity());
                case HttpStatus.SC_NOT_FOUND:
                    throw new RuntimeException("No Found.");
                default:
                    throw new RuntimeException("Connection Error.");
                }
            }
        });
        return result;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.ibm.watson.developer_cloud.service.WatsonService.java

/**
 * Gets the thread safe client./*  w  w  w .  j ava2 s .c  om*/
 * 
 * @return the thread safe client
 */
private HttpClient getThreadSafeClient() {

    DefaultHttpClient client = new DefaultHttpClient(getDefaultRequestParams());
    ClientConnectionManager mgr = client.getConnectionManager();
    HttpParams params = client.getParams();

    client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);

    return client;
}

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {//from   w  w w.  j  ava2 s.  c om
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java

/**
 * ??????????//w  w w  .  ja v a  2 s . com
 * 
 * @param url
 * @return
 * @throws Exception
 */
BufferedImage getFittingImage(String url) throws Exception {
    // ??
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = buildDefaultHttpMessage(new HttpGet(url));
    httpget.setHeader("Referer", "http://www.bijint.com/jp/");
    HttpResponse response = httpclient.execute(httpget);

    BufferedImage image = ImageIO.read(response.getEntity().getContent());
    httpclient.getConnectionManager().shutdown();

    int width = image.getWidth() / 10 * 4;
    int height = image.getHeight() / 10 * 4;
    BufferedImage resizedImage = null;
    resizedImage = new BufferedImage(width, height, image.getType());
    resizedImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 0,
            0, width, height, null);
    return resizedImage;
}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientUtil.java

private static void configureProxy(final DefaultHttpClient httpClient, final String ctxPrefix,
        final RemoteStorageContext ctx, final Logger logger) {
    final RemoteProxySettings rps = ctx.getRemoteProxySettings();

    if (rps.isEnabled()) {
        logger(logger).info("... proxy setup with host '{}'", rps.getHostname());

        final HttpHost proxy = new HttpHost(rps.getHostname(), rps.getPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        // check if we have non-proxy hosts
        if (rps.getNonProxyHosts() != null && !rps.getNonProxyHosts().isEmpty()) {
            final Set<Pattern> nonProxyHostPatterns = new HashSet<Pattern>(rps.getNonProxyHosts().size());
            for (String nonProxyHostRegex : rps.getNonProxyHosts()) {
                try {
                    nonProxyHostPatterns.add(Pattern.compile(nonProxyHostRegex, Pattern.CASE_INSENSITIVE));
                } catch (PatternSyntaxException e) {
                    logger(logger).warn("Invalid non proxy host regex: {}", nonProxyHostRegex, e);
                }/*from  www  .j  a  v  a  2 s. c om*/
            }
            httpClient.setRoutePlanner(new NonProxyHostsAwareHttpRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), nonProxyHostPatterns));

        }

        configureAuthentication(httpClient, ctxPrefix, ctx, rps.getProxyAuthentication(), logger, "proxy ");

        if (rps.getProxyAuthentication() != null) {
            if (ctx.getRemoteAuthenticationSettings() != null
                    && (ctx.getRemoteAuthenticationSettings() instanceof NtlmRemoteAuthenticationSettings)) {
                logger(logger).warn("... Apache Commons HttpClient 3.x is unable to use NTLM auth scheme\n"
                        + " for BOTH server side and proxy side authentication!\n"
                        + " You MUST reconfigure server side auth and use BASIC/DIGEST scheme\n"
                        + " if you have to use NTLM proxy, otherwise it will not work!\n"
                        + " *** SERVER SIDE AUTH OVERRIDDEN");
            }

        }
    }
}

From source file:net.heroicefforts.viable.android.rep.jira.JIRARepository.java

private JIRARepository(String appName, String location) throws CreateException {
    if (location == null)
        throw new CreateException("No '" + "viable-provider-location"
                + "' meta-data field defined for application.  JIRA Repository cannot be constructed.");

    this.rootURL = location;
    this.appName = appName;

    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry schemes = client.getConnectionManager().getSchemeRegistry();
    BasicHttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
    httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemes), params);
}