Example usage for org.apache.http.client HttpClient getConnectionManager

List of usage examples for org.apache.http.client HttpClient getConnectionManager

Introduction

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

Prototype

@Deprecated
ClientConnectionManager getConnectionManager();

Source Link

Document

Obtains the connection manager used by this client.

Usage

From source file:HttpsRequestDemo.java

private void registerSSLSocketFactory(HttpClient httpclient) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    // E:\\cer\\cpic_jttp.keystore
    FileInputStream instream = new FileInputStream(
            new File("E:\\Program Files\\Java\\jdk1.7.0_21\\bin\\cpic_jttp.keystore"));
    try {/*  ww  w  .  j a va 2s  .co  m*/
        trustStore.load(instream, "cpicJttp".toCharArray());
    } finally {
        instream.close();
    }

    SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
    Scheme sch = new Scheme("https", socketFactory, 443);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
}

From source file:com.universalmind.core.components.mockup.loremipsum.LoremIpsumService.java

@Test
public void testService() {
    Integer paragraphs = 2;//from   w  ww  .  j av a  2s. com

    String loremText = null;
    String url = null;
    url = "http://www.lipsum.com/feed/xml?what=paras&start=true&amount=" + paragraphs;

    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(url);

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);

        loremText = parseLoremIpsum(responseBody);

        Assert.assertNotNull(loremText);
        Assert.assertTrue(loremText.length() > 100);
    } catch (Exception jse) {
        //do nothing
        jse.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.jboss.as.test.integration.web.security.cert.WebSecurityCERTTestCase.java

protected void makeCall(String alias, int expectedStatusCode) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient = wrapClient(httpclient, alias);
    try {//from www . j  a  va2 s.  co  m
        HttpGet httpget = new HttpGet(
                "https://" + mgmtClient.getMgmtAddress() + ":8380/web-secure-client-cert/secured/");
        HttpResponse response = httpclient.execute(httpget);

        StatusLine statusLine = response.getStatusLine();
        System.out.println("Response: " + statusLine);
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:us.mn.state.health.lims.common.externalLinks.ExternalPatientSearch.java

protected void doSearch() {

    HttpClient httpclient = new DefaultHttpClient();
    setTimeout(httpclient);//from   w  w w .j  a v a 2  s .  c  o  m

    HttpGet httpget = new HttpGet(connectionString);
    URI getUri = buildConnectionString(httpget.getURI());
    httpget.setURI(getUri);

    try {
        // Ignore hostname mismatches and allow trust of self-signed certs
        SSLSocketFactory sslsf = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sslsf);
        ClientConnectionManager ccm = httpclient.getConnectionManager();
        ccm.getSchemeRegistry().register(https);

        HttpResponse getResponse = httpclient.execute(httpget);
        returnStatus = getResponse.getStatusLine().getStatusCode();
        setPossibleErrors();
        setResults(IOUtils.toString(getResponse.getEntity().getContent(), "UTF-8"));
    } catch (SocketTimeoutException e) {
        errors.add("Response from patient information server took too long.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        // System.out.println("Tinny time out" + e);
    } catch (ConnectException e) {
        errors.add("Unable to connect to patient information form service. Service may not be running");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        // System.out.println("you no talks? " + e);
    } catch (IOException e) {
        errors.add("IO error trying to read input stream.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        // System.out.println("all else failed " + e);
    } catch (KeyManagementException e) {
        errors.add("Key management error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (UnrecoverableKeyException e) {
        errors.add("Unrecoverable key error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (NoSuchAlgorithmException e) {
        errors.add("No such encyrption algorithm error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (KeyStoreException e) {
        errors.add("Keystore error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (RuntimeException e) {
        errors.add("Runtime error trying to retrieve patient information.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        httpget.abort();
        throw e;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.openrepose.core.services.httpclient.impl.HttpConnectionPoolServiceImpl.java

@Override
public HttpClientResponse getClient(String clientId) throws HttpClientNotFoundException {

    if (poolMap.isEmpty()) {
        defaultClientId = DEFAULT_POOL_ID;
        HttpClient httpClient = clientGenerator(DEFAULT_POOL);
        poolMap.put(defaultClientId, httpClient);
    }/*  w w  w.j  a va 2  s. c om*/

    if (clientId != null && !clientId.isEmpty() && !isAvailable(clientId)) {
        HttpClient httpClient = clientGenerator(DEFAULT_POOL);
        poolMap.put(clientId, httpClient);
    }

    final HttpClient requestedClient;

    if (clientId == null || clientId.isEmpty()) {
        requestedClient = poolMap.get(defaultClientId);
    } else {
        if (isAvailable(clientId)) {
            requestedClient = poolMap.get(clientId);
        } else {
            throw new HttpClientNotFoundException("Pool " + clientId + "not available");
        }
    }

    String clientInstanceId = requestedClient.getParams().getParameter(CLIENT_INSTANCE_ID).toString();
    String userId = httpClientUserManager.addUser(clientInstanceId);

    PoolStats poolStats = ((PoolingClientConnectionManager) requestedClient.getConnectionManager())
            .getTotalStats();
    LOG.trace("Client requested, pool currently leased: {}, available: {}, pending: {}, max: {}",
            poolStats.getLeased(), poolStats.getAvailable(), poolStats.getPending(), poolStats.getMax());

    return new HttpClientResponseImpl(requestedClient, clientId, clientInstanceId, userId);
}

From source file:org.deegree.feature.persistence.geocouch.GeoCouchFeatureStore.java

private Feature getFeatureById(String id) {
    BlobCodec codec = new BlobCodec(schema.getGMLSchema().getVersion(), NONE);
    HttpClient client = new DefaultHttpClient();
    try {/* w  ww.  java2  s.c o  m*/
        HttpGet get = new HttpGet(couchUrl + id + "/feature");
        HttpResponse resp = client.execute(get);
        return (Feature) codec.decode(resp.getEntity().getContent(), schema.getNamespaceBindings(), schema, crs,
                null);
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().shutdown();
    }
    return null;
}

From source file:org.sociotech.communitymashup.framework.java.apiwrapper.CommunityMashupApi.java

/**
 * Processes a post request against the given url.
 * /*from   w  ww.  j  a  v  a2s.c  om*/
 * @param url
 *            Url for the get request.
 * @param parameterString All parameters serialized in a string
 * @return The response as string
 * @throws MashupConnectionException
 *             If connection was not successful
 */
private String doPost(String url, String parameterString) throws MashupConnectionException {
    String result = null;

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    try {
        post.setEntity(new StringEntity(parameterString));
        result = httpClient.execute(post, responseHandler);
    } catch (Exception e) {
        throw new MashupConnectionException(e, url);
    } finally {
        // client is no longer needed
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:net.datacrow.onlinesearch.discogs.task.DiscogsMusicSearch.java

@Override
protected DcObject getItem(Object key, boolean full) throws Exception {
    HttpClient httpClient = getHttpClient();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost("api.discogs.com");
    builder.setPath("/release/" + key);
    URI uri = builder.build();/*  w  ww . j  a va  2s . co  m*/
    HttpGet httpGet = new HttpGet(uri);

    HttpOAuthHelper au = new HttpOAuthHelper("application/json");
    au.handleRequest(httpGet, _CONSUMER_KEY, _CONSUMER_SECRET);

    HttpResponse httpResponse = httpClient.execute(httpGet);
    String response = getReponseText(httpResponse);
    httpClient.getConnectionManager().shutdown();

    MusicAlbum ma = new MusicAlbum();

    ma.addExternalReference(DcRepository.ExternalReferences._DISCOGS, (String) key);
    ma.setValue(DcObject._SYS_SERVICEURL, uri.toString());

    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(response);
    JsonObject eRespone = jsonObject.getAsJsonObject("resp");
    JsonObject eRelease = eRespone.getAsJsonObject("release");

    if (eRelease != null) {
        ma.setValue(MusicAlbum._A_TITLE, eRelease.get("title").getAsString());
        ma.setValue(MusicAlbum._C_YEAR, eRelease.get("year").getAsString());
        ma.setValue(MusicAlbum._N_WEBPAGE, eRelease.get("uri").getAsString());

        ma.createReference(MusicAlbum._F_COUNTRY, eRelease.get("country").getAsString());

        setStorageMedium(ma, eRelease);
        setRating(ma, eRelease);
        setGenres(ma, eRelease);
        setArtists(ma, eRelease);
        addTracks(ma, eRelease);
        setImages(ma, eRelease);
    }

    Thread.sleep(1000);
    return ma;
}

From source file:com.dalaran.async.task.http.AbstractHTTPService.java

private String responseToBuffer(HttpClient client, HttpEntity entity) throws IOException {
    StringBuilder response = new StringBuilder();
    if (entity != null) {
        InputStream inputStream = entity.getContent();
        try {// w w w . j  a va  2  s  . co m
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                response.append(temp);
            }
        } finally {
            try {
                inputStream.close();
                client.getConnectionManager().shutdown();
            } catch (IOException e) {
                Log.e(this.getClass().getSimpleName(), e.getMessage());
                //do nothing
            }
        }
    } else {
        throw new IOException("Got empty response!");
    }
    return response.toString();
}