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:nl.esciencecenter.octopus.webservice.JobLauncherService.java

/**
 * Enable insecure SSL in http client like self signed certificates.
 *
 * @param httpClient/*from  w ww  . j a va  2 s . c  om*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public void useInsecureSSL(HttpClient httpClient)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory socketFactory;
    socketFactory = new SSLSocketFactory(new TrustStrategy() {

        public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy...
            return true;
        }

    }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry registry = httpClient.getConnectionManager().getSchemeRegistry();
    registry.register(new Scheme("https", 443, socketFactory));
}

From source file:ch.entwine.weblounge.test.harness.rest.SearchEndpointTest.java

/**
 * Performs a search request for non-existing content.
 * /*from   www  .j  a  v  a  2  s. co  m*/
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void searchNonExisting(String serverUrl) throws Exception {
    logger.info("Preparing test of search rest api");

    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/search");

    // Prepare the request
    logger.info("Searching for a page");
    HttpGet searchRequest = new HttpGet(requestUrl);

    // Send the request. The response should be a 400 (bad request)
    logger.debug("Sending empty get request to {}", searchRequest.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
        assertEquals(0, response.getEntity().getContentLength());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for search terms that don't yield a result
    String searchTerms = "xyz";
    httpClient = new DefaultHttpClient();
    searchRequest = new HttpGet(UrlUtils.concat(requestUrl, searchTerms));
    logger.info("Sending search request for '{}' to {}", searchTerms, requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document xml = TestUtils.parseXMLResponse(response);
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@documents"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@hits"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@offset"));
        assertEquals("1", XPathHelper.valueOf(xml, "/searchresult/@page"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@pagesize"));
        assertEquals("0", XPathHelper.valueOf(xml, "count(/searchresult/result)"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.camel.itest.osgi.cxf.blueprint.CxfRsBlueprintRouterTest.java

@Test
public void testPostConsumer() throws Exception {
    HttpPost post = new HttpPost("http://localhost:9000/route/customerservice/customers");
    post.addHeader("Accept", "text/xml");
    StringEntity entity = new StringEntity(POST_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    post.setEntity(entity);//from  w w  w .  ja v a 2  s .  co m
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(post);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>124</id><name>Jack</name></Customer>",
                EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method,
        String xml) {/*from w  w w . j a v  a 2  s. co  m*/

    String reqURL = "https://" + ip + ":" + port + action;
    //      Map<String, String> params = null;
    long responseLength = 0; // ?
    String responseContent = null; // ?

    HttpClient httpClient = new DefaultHttpClient(); // httpClient
    httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    X509TrustManager xtm = new X509TrustManager() { // TrustManager
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        // TLS1.0SSL3.0??TLSSSL?SSLContext
        SSLContext ctx = SSLContext.getInstance("TLS");

        // TrustManager??TrustManager?SSLSocket
        ctx.init(null, new TrustManager[] { xtm }, null);

        // SSLSocketFactory
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

        // SchemeRegistrySSLSocketFactoryHttpClient
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", port, socketFactory));

        HttpPost httpPost = new HttpPost(reqURL); // HttpPost

        // add the 3 headers below
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
        httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        httpPost.addHeader("uuid", "itest");// for editor token of DR-Api

        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8
        httpPost.setEntity(requestBody);
        log.info(">> Request URI: " + httpPost.getRequestLine().getUri());

        HttpResponse response = httpClient.execute(httpPost); // POST
        HttpEntity entity = response.getEntity(); // ??

        if (null != entity) {
            responseLength = entity.getContentLength();

            String contentEncoding = null;
            Header ce = response.getEntity().getContentEncoding();
            if (ce != null) {
                contentEncoding = ce.getValue();
            }

            if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
                GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
                Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                while (in.hasNextLine()) {
                    sb.append(in.nextLine()).append(System.getProperty("line.separator"));
                }
                responseContent = sb.toString();
            } else {
                responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

            EntityUtils.consume(entity); // Consume response content
        }
        log.info("?: " + httpPost.getURI());
        log.info("??: " + response.getStatusLine());
        log.info("?: " + responseLength);
        log.info("?: " + responseContent);
    } catch (KeyManagementException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        log.error(e.getMessage(), e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown(); // ,?
        return responseContent;
    }
}

From source file:org.cm.podd.report.util.RequestDataUtil.java

public static ResponseObject post(String path, String query, String json, String token) {
    JSONObject jsonObj = null;//from w  ww  . j a v  a 2s .  c  o m
    int statusCode = 0;

    //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0);
    String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);
    String reqUrl = "";

    if (path.contains("http://") || path.contains("https://")) {
        reqUrl = String.format("%s%s", path, query == null ? "" : "?" + query);
    } else {
        reqUrl = String.format("%s%s%s", serverUrl, path, query == null ? "" : "?" + query);
    }

    Log.i(TAG, "submit url=" + reqUrl);
    Log.i(TAG, "post data=" + json);

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);

    try {
        HttpPost post = new HttpPost(reqUrl);
        post.setHeader("Content-Type", "application/json");
        if (token != null) {
            post.setHeader("Authorization", "Token " + token);
        }
        post.setEntity(new StringEntity(json, HTTP.UTF_8));

        HttpResponse response;
        response = client.execute(post);
        HttpEntity entity = response.getEntity();

        // Detect server complaints
        statusCode = response.getStatusLine().getStatusCode();
        Log.v(TAG, "status code=" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED
                || statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            InputStream in = entity.getContent();
            String resp = FileUtil.convertInputStreamToString(in);

            jsonObj = new JSONObject(resp);
            entity.consumeContent();
        }

    } catch (ClientProtocolException e) {
        Log.e(TAG, "error post data", e);
    } catch (IOException e) {
        Log.e(TAG, "Can't connect server", e);
    } catch (JSONException e) {
        Log.e(TAG, "error convert json", e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return new ResponseObject(statusCode, jsonObj);
}

From source file:com.google.apphosting.vmruntime.VmApiProxyDelegate.java

VmApiProxyDelegate(HttpClient httpclient) {
    this.defaultTimeoutMs = DEFAULT_RPC_TIMEOUT_MS;
    this.executor = Executors.newCachedThreadPool();
    this.httpclient = httpclient;
    this.monitorThread = new IdleConnectionMonitorThread(httpclient.getConnectionManager());
    this.monitorThread.start();
}

From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected RemoteTask remoteImport(DBAttachment target) throws Exception {
    Reference uri = new Reference(queryService);

    HttpClient client = createHTTPClient(uri.getHostDomain(), uri.getHostPort());
    RemoteTask task = new RemoteTask(client, new URL(String.format("%s/dataset", queryService)),
            "text/uri-list", createPOSTEntity(attachment), HttpPost.METHOD_NAME);

    try {//  ww w  . j  a  v  a2  s  .c o m
        task = wait(task, System.currentTimeMillis());
        String dataset_uri = "dataset_uri";
        URL dataset = task.getResult();
        if (task.isCompletedOK()) {
            if (!"text/uri-list".equals(attachment.getFormat())) { //was a file
                //now post the dataset uri to get the /R datasets (query table)
                attachment.setFormat("text/uri-list");
                attachment.setDescription(dataset.toExternalForm());
                task = new RemoteTask(client, new URL(String.format("%s/dataset", queryService)),
                        "text/uri-list", createPOSTEntity(attachment), HttpPost.METHOD_NAME);
                task = wait(task, System.currentTimeMillis());
            }

            Form form = new Form();
            form.add(dataset_uri, dataset.toURI().toString());
            for (String algorithm : algorithms) { //just launch tasks and don't wait
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                formparams.add(new BasicNameValuePair(dataset_uri, dataset.toURI().toString()));
                HttpEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpClient newclient = createHTTPClient(uri.getHostDomain(), uri.getHostPort());
                try {
                    new RemoteTask(newclient, new URL(String.format("%s%s", queryService, algorithm)),
                            "text/uri-list", entity, HttpPost.METHOD_NAME);

                } catch (Exception x) {
                } finally {
                    try {
                        newclient.getConnectionManager().shutdown();
                    } catch (Exception x) {
                    }
                }
            }
        }

    } catch (Exception x) {
        task.setError(new ResourceException(Status.SERVER_ERROR_BAD_GATEWAY,
                String.format("Error importing chemical structures dataset to %s", uri), x));
    } finally {
        try {
            client.getConnectionManager().shutdown();
        } catch (Exception x) {
        }
    }
    return task;
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java

/** send a GET Request and return the response as string */
String sendGetRequest(String url) throws Exception {
    String sresponse;//from w  ww. ja v  a 2s .c o  m
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    // set authentification header
    httpget.addHeader("Authorization", authHeader);

    HttpResponse response = httpclient.execute(httpget);

    // check status code
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Bibsonomy Error", XMLUtils.parseError(sresponse));
    }
    return sresponse;
}

From source file:ch.entwine.weblounge.test.harness.content.CacheTest.java

/**
 * {@inheritDoc}//from w  ww  .  ja va  2s .c o  m
 * 
 * @see ch.entwine.weblounge.testing.kernel.IntegrationTest#execute(java.lang.String)
 */
@Override
public void execute(String serverUrl) throws Exception {
    logger.info("Testing if response cache is activated");

    // Test if the cache is active
    logger.info("Sending request to determine cache status to {}", serverUrl);
    HttpGet request = new HttpGet(serverUrl);
    request.addHeader("X-Cache-Debug", "yes");
    String[][] params = new String[][] { {} };

    // Send and the request and examine the response twice to make sure to get
    // a cached response is available
    boolean cacheIsActive = false;
    for (int i = 0; i < 2; i++) {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = TestUtils.request(httpClient, request, params);
            cacheIsActive = response.getHeaders("X-Cache-Key").length > 0;
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }

    if (!cacheIsActive) {
        logger.warn("Response cache is not available and won't be tested");
        return;
    }

    logger.warn("Response cache is active");
    testCacheHeaders(serverUrl);
    testInheritedModifcation(serverUrl);
    testPageletModifcationDate(serverUrl);
}

From source file:com.lonepulse.travisjr.net.ZombieConfig.java

@Override
public HttpClient httpClient() {

    HttpClient client = super.httpClient();

    try {/*w ww  .j a va 2 s  . co  m*/

        KeyStore keyStore = KeyStore.getInstance("BKS");
        InputStream is = TravisJr.Application.getContext().getResources().openRawResource(R.raw.travisjr);

        try {

            keyStore.load(is, null);
        } finally {

            is.close();
        }

        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(keyStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        SchemeRegistry schemeRegistry = ((ThreadSafeClientConnManager) client.getConnectionManager())
                .getSchemeRegistry();

        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
    } catch (Exception e) {

        Log.e(getClass().getSimpleName(), "HttpClient configuration with a custom SSLSocketFactory failed.", e);
    }

    return client;
}