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.opencastproject.remotetest.server.DigestAuthenticationTest.java

@Test
public void testUnauthenticatedGet() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet get = new HttpGet(BASE_URL + "/welcome.html");
    try {// www . j  av  a  2s  .  c  om
        HttpResponse response = httpclient.execute(get);
        String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        Assert.assertTrue(content.contains("Login Page"));
        Assert.assertTrue(!content.contains("Start Climbing"));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.ebayopensource.twin.TwinConnection.java

private HttpClient getClient() {
    synchronized (TwinConnection.class) {
        if (connManager == null) {
            DefaultHttpClient client = new DefaultHttpClient();
            params = client.getParams().copy();
            params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(50));
            params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200);
            connManager = new ThreadSafeClientConnManager(params,
                    client.getConnectionManager().getSchemeRegistry());
        }/* w  ww.j ava 2  s .  c  o  m*/
    }
    DefaultHttpClient client = new DefaultHttpClient(connManager, params);
    client.setRedirectHandler(new DefaultRedirectHandler());
    return client;
}

From source file:org.opencastproject.remotetest.server.DigestAuthenticationTest.java

@Test
public void testBadDigestAuthenticatedGet() throws Exception {
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account",
            "wrong_password");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    HttpGet get = new HttpGet(BASE_URL + "/welcome.html");
    get.addHeader("X-Requested-Auth", "Digest");
    try {/*from  w  ww . j  ava 2  s . c o m*/
        HttpResponse response = httpclient.execute(get);
        Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.brightcove.zartan.encode.TencodeAPI.java

private JsonNode encodeFile(TranscodeInfo transcode, URI transcodeApiUrl, VerifiableTranscode toVerify) {

    HttpPost method = new HttpPost(transcodeApiUrl);

    String json = getJson(transcode, toVerify);
    System.out.println(json);/*from  www .j a v  a2 s.co m*/

    StringEntity entity;
    try {
        entity = new StringEntity(json);

        entity.setContentType("application/json");

        method.setEntity(entity);

        HttpResponse response = null;
        DefaultHttpClient httpAgent = new DefaultHttpClient();

        response = httpAgent.execute(method);

        // Make sure the HTTP communication was OK (not the same as an error in the Media API
        // reponse)
        Integer statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpAgent.getConnectionManager().shutdown();
            // TODO:throw inteligent failure
            return null;
        }

        // Parse the response
        HttpEntity resentity = response.getEntity();
        JsonNode jsonObj = getJSONFromEntity(resentity);
        httpAgent.getConnectionManager().shutdown();
        return jsonObj;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java

private HttpClient getHttpClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (useJreProxy) {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        httpclient.setRoutePlanner(routePlanner);
    }//from w  w  w. j  a v  a 2  s  .c om
    return httpclient;
}

From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java

public static String get(String url, Cookie[] cookies) {
    String body = null;/* w  ww . j  a  v  a 2 s.c  o  m*/
    try {
        StringBuffer buffer = new StringBuffer();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);

        httpClient.setCookieStore(new BasicCookieStore());
        for (int i = 0; i < cookies.length; i++) {
            logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":"
                    + cookies[i].getDomain() + ":" + cookies[i].getPath());
            BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue());
            cookie.setVersion(0);
            URL urlParse = new URL(url);
            String host = urlParse.getHost();
            String domain = null;
            if (host != null && host.indexOf('.') > 0) {
                domain = host.substring(host.indexOf('.') + 1);
            }
            logger.finest("Domain:" + domain);
            cookie.setDomain(domain);
            cookie.setPath("/");

            httpClient.getCookieStore().addCookie(cookie);
        }
        HttpResponse response = httpClient.execute(getRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        logger.finest("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.finest(output);
            buffer.append(output);
        }

        httpClient.getConnectionManager().shutdown();

        body = buffer.toString();

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

    return body;
}

From source file:org.jssec.android.https.privatecertificate.PrivateCertificateHttpsGet.java

@Override
protected Object doInBackground(String... params) {

    DefaultHttpClient client = new DefaultHttpClient();

    try {//w ww . j a v a2  s .  co m
        // ?1 ???
        // assets??????????KeyStoreclient?
        KeyStore ks = KeyStoreUtil.getEmptyKeyStore();
        KeyStoreUtil.loadX509Certificate(ks, mContext.getResources().getAssets().open("cacert.crt"));
        Scheme sch = new Scheme("https", new SSLSocketFactory(ks), 443);
        client.getConnectionManager().getSchemeRegistry().register(sch);

        // ?2 URI?https://??
        // ?3 ???????
        HttpGet request = new HttpGet(params[0]);
        HttpResponse response = client.execute(request);
        checkResponse(response);

        // ?4 ?????????
        return EntityUtils.toByteArray(response.getEntity());
    } catch (SSLException e) {
        // ?5 SSLException?????????
        // ??????
        return e;
    } catch (Exception e) {
        return e;
    } finally {
        // ?HttpClientshutdown?
        client.getConnectionManager().shutdown();
    }
}

From source file:com.brightcove.zartan.encode.ZencodeAPI.java

private JsonNode encodeFile(TranscodeInfo transcode, URI transcodeApiUrl, ZencoderCredentials zc) {

    HttpPost method = new HttpPost(transcodeApiUrl);
    BasicHeader keyHeader = new BasicHeader("Zencoder-Api-Key", zc.getApiKey());

    method.addHeader(keyHeader);/*from  w  w w.j a va 2 s  .c o m*/

    String json = getJson(transcode);
    System.out.println(json);

    StringEntity entity;
    try {
        entity = new StringEntity(json);

        entity.setContentType("application/json");

        method.setEntity(entity);

        HttpResponse response = null;
        DefaultHttpClient httpAgent = new DefaultHttpClient();

        response = httpAgent.execute(method);

        // Make sure the HTTP communication was OK (not the same as an error in the Media API
        // reponse)
        Integer statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 201) {
            httpAgent.getConnectionManager().shutdown();
            // TODO:throw inteligent failure
            return null;
        }

        // Parse the response
        HttpEntity resentity = response.getEntity();
        JsonNode jsonObj = getJSONFromEntity(resentity);
        httpAgent.getConnectionManager().shutdown();
        return jsonObj;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:com.google.code.maven.plugin.http.client.transformer.JiraRssLinkedIssuesEnricher.java

private String queryForJira(String jira) throws MojoExecutionException, ClientProtocolException, IOException {
    RequestBeanDefinition requestConfiguration = beanFactory.getBean(RequestBeanDefinition.class);
    Request request = requestConfiguration.create(beanFactory);
    for (Parameter parameter : request.getParameters()) {
        if ("jqlQuery".equals(parameter.getName())) {
            parameter.setValue("id=" + jira);
            break;
        }/* w  w w .j av a  2  s.c o  m*/
    }
    Proxy proxy = null;
    try {
        ProxyBeanDefinition proxyConfiguration = beanFactory.getBean(ProxyBeanDefinition.class);
        proxy = proxyConfiguration.create(beanFactory);
    } catch (BeansException be) {
        proxy = null;
    }
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = HttpRequestUtils.query(httpclient, request, proxy, getLog());
    String content = httpEntityContentToString.transform(response, log);
    httpclient.getConnectionManager().shutdown();

    int start = content.indexOf(ITEM_START_TAG);
    if (start > 0) {
        int end = content.indexOf(ITEM_END_TAG);
        if (end > 0) {
            return content.substring(start, end + ITEM_END_TAG.length());
        }
    }
    return null;
}

From source file:net.zypr.api.Protocol.java

private DefaultHttpClient getHTTPClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", _socketFactory, 443));
    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");
            }//  w w  w.  j  a va  2  s.  c o  m
        }
    });
    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int index = 0; index < codecs.length; index++)
                    if (codecs[index].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
            }
        }
    });
    return (httpclient);
}