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:test.Http.java

public static String postRequest(String url, String reqJson) {
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpEntity httpEntity = null;/*  w  w  w  . ja v  a2  s.  com*/
    try {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("requestJson", reqJson));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        HttpResponse httpResponse = httpclient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                // 
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(httpEntity.getContent(), "UTF-8"));
                String line = null;
                result = "";
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
            }
        }
    } catch (IOException e) {
        if (httpEntity != null) {
            try {
                String returnJson = EntityUtils.toString(httpEntity);
                result = returnJson;
            } catch (ParseException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:org.apache.solr.client.solrj.impl.BasicHttpSolrServerTest.java

@Test
public void testSetParametersExternalClient() {
    HttpClient client = HttpClientUtil.createClient(null);
    HttpSolrServer server = new HttpSolrServer(jetty.getBaseUrl().toString(), client);
    try {/*from  w  w w . j av a2  s. c  o m*/
        server.setMaxTotalConnections(1);
        fail("Operation should not succeed.");
    } catch (UnsupportedOperationException e) {
    }
    try {
        server.setDefaultMaxConnectionsPerHost(1);
        fail("Operation should not succeed.");
    } catch (UnsupportedOperationException e) {
    }
    server.shutdown();
    client.getConnectionManager().shutdown();
}

From source file:org.jboss.as.test.clustering.cluster.web.passivation.SessionPassivationAbstractCase.java

/**
 * Tests the ability to passivate session when maximum number of active sessions (max-active-sessions) reached.
 *
 * @throws Exception/*from www .j a  va2  s. com*/
 */
@Test
@Ignore("https://issues.jboss.org/browse/AS7-4490")
public void testSessionPassivationWithMaxActiveSessions(
        @ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1) throws Exception {

    // Create an instance of HttpClient
    HttpClient client = HttpClientUtils.relaxedCookieHttpClient();
    try {
        // Setup the session
        HttpResponse response = ClusterHttpClientUtil.tryGet(client, baseURL1 + SimpleServlet.URL);
        response.getEntity().getContent().close();

        // Get the Attribute set; confirm session wasn't deserialized
        response = ClusterHttpClientUtil.tryGet(client, baseURL1 + SimpleServlet.URL);
        Assert.assertFalse("Session should not be serialized",
                Boolean.valueOf(response.getFirstHeader(SimpleServlet.HEADER_SERIALIZED).getValue()));
        response.getEntity().getContent().close();

        // passivation-min-idle-time is set to 5 seconds, so wait long enough
        // so that the session can be passivated
        Thread.sleep(PASSIVATION_MIN_IDLE_TIME + 1000);

        // Create enough sessions on the server to trigger passivation
        // knowing that max-active-sessions is set to 20 in jboss-web.xml
        for (int i = 0; i < MAX_ACTIVE_SESSIONS; i++) {
            HttpClient maxActiveClient = new DefaultHttpClient();

            try {
                response = ClusterHttpClientUtil.tryGet(maxActiveClient, baseURL1 + SimpleServlet.URL);
                Assert.assertFalse("Session should not be serialized",
                        Boolean.valueOf(response.getFirstHeader(SimpleServlet.HEADER_SERIALIZED).getValue()));
                Assert.assertEquals("The session should be new", 1,
                        Integer.parseInt(response.getFirstHeader("value").getValue()));
                response.getEntity().getContent().close();

                response = ClusterHttpClientUtil.tryGet(maxActiveClient, baseURL1 + SimpleServlet.URL);
                response.getEntity().getContent().close();
            } finally {
                maxActiveClient.getConnectionManager().shutdown();
            }
        }

        // Now access the session and confirm that it was deserialized (passivated then activated)
        // Activate the session by requesting the attribute
        response = ClusterHttpClientUtil.tryGet(client, baseURL1 + SimpleServlet.URL);
        Assert.assertTrue("Session should have activated and have been deserialized",
                Boolean.valueOf(response.getFirstHeader(SimpleServlet.HEADER_SERIALIZED).getValue()));
        Assert.assertEquals(3, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.sugestio.client.SugestioClient.java

/**
 * Performs a GET request and returns the response body as a JsonElement.
 * @param resource the resource to get//from w w  w.  j  a v  a2 s. c  o  m
 * @param parameters query string parameters
 * @param raise404 if true, a HTTP response of 404 will raise an exception, if false, the method will return null
 * @return JsonElement
 * @throws Exception
 */
private JsonElement doGet(String resource, Map<String, String> parameters, boolean raise404) throws Exception {

    HttpClient httpClient = new DefaultHttpClient();
    String uri = getUri(resource);

    if (parameters != null && parameters.size() > 0) {

        List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
        for (String key : parameters.keySet()) {
            queryParams.add(new BasicNameValuePair(key, parameters.get(key)));
        }

        uri += "?" + URLEncodedUtils.format(queryParams, "UTF-8");
    }

    try {

        HttpGet httpGet = new HttpGet(uri);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        String body = EntityUtils.toString(httpResponse.getEntity());
        int code = httpResponse.getStatusLine().getStatusCode();

        if (code == 200) {
            httpClient.getConnectionManager().shutdown();
            JsonParser parser = new JsonParser();
            return parser.parse(body);
        } else if (code == 404 && !raise404) {
            httpClient.getConnectionManager().shutdown();
            return null;
        } else {
            String message = "Response code " + httpResponse.getStatusLine().getStatusCode() + ". ";
            message += body;
            throw new Exception(message);
        }

    } catch (Exception e) {
        httpClient.getConnectionManager().shutdown();
        throw e;
    }

}

From source file:org.semantictools.web.upload.AppspotUploadClient.java

public void upload(String contentType, String path, File file) throws IOException {

    if (file.getName().equals(CHECKSUM_PROPERTIES)) {
        return;//from w ww  .j a v  a 2s.  com
    }

    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    // Do not upload if we can confirm that we previously uploaded
    // the same content.

    String checksumKey = path.concat(".sha1");
    String checksumValue = null;
    try {
        checksumValue = Checksum.sha1(file);
        String prior = checksumProperties.getProperty(checksumKey);
        if (checksumValue.equals(prior)) {
            return;
        }

    } catch (NoSuchAlgorithmException e) {
        // Ignore.
    }

    logger.debug("uploading... " + path);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(servletURL);
    post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx",
            Charset.forName("UTF-8"));

    FileBody body = new FileBody(file, contentType);

    entity.addPart(CONTENT_TYPE, new StringBody(contentType));
    entity.addPart(PATH, new StringBody(path));
    if (version != null) {
        entity.addPart(VERSION, new StringBody(version));
    }
    entity.addPart(FILE_UPLOAD, body);

    post.setEntity(entity);

    String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");

    client.getConnectionManager().shutdown();

    if (checksumValue != null) {
        checksumProperties.put(checksumKey, checksumValue);
    }

}

From source file:tern.server.nodejs.NodejsTernHelper.java

public static JsonObject makeRequest(String baseURL, TernDoc doc, boolean silent,
        List<IInterceptor> interceptors, ITernServer server) throws IOException, TernException {
    TernQuery query = doc.getQuery();//from  ww w  . j a  v a2  s.  c om
    String methodName = query != null ? query.getLabel() : "";
    long startTime = 0;
    if (interceptors != null) {
        startTime = System.nanoTime();
        for (IInterceptor interceptor : interceptors) {
            interceptor.handleRequest(doc, server, methodName);
        }
    }
    HttpClient httpClient = new DefaultHttpClient();
    try {
        // Post JSON Tern doc
        HttpPost httpPost = createHttpPost(baseURL, doc);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();
        InputStream in = entity.getContent();
        // Check the status
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            // node.js server throws error
            String message = IOUtils.toString(in);
            if (StringUtils.isEmpty(message)) {
                throw new TernException(statusLine.toString());
            }
            throw TernExceptionFactory.create(message);
        }

        try {
            JsonObject response = (JsonObject) Json.parse(new InputStreamReader(in, UTF_8));
            if (interceptors != null) {
                for (IInterceptor interceptor : interceptors) {
                    interceptor.handleResponse(response, server, methodName, getElapsedTimeInMs(startTime));
                }
            }
            return response;
        } catch (ParseException e) {
            throw new IOException(e);
        }
    } catch (Exception e) {
        if (interceptors != null) {
            for (IInterceptor interceptor : interceptors) {
                interceptor.handleError(e, server, methodName, getElapsedTimeInMs(startTime));
            }
        }
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        if (e instanceof TernException) {
            throw (TernException) e;
        }
        throw new TernException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.itude.mobile.mobbl.core.services.datamanager.handlers.MBRESTServiceDataHandler.java

private void allowAnyCertificate(HttpClient httpClient)
        throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {

        @Override/*from   www.j a va  2  s .com*/
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = httpClient.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
}

From source file:org.apache.camel.component.cxf.jaxrs.CxfRsRouterTest.java

@Test
public void testGetCustomers() throws Exception {
    HttpGet get = new HttpGet(
            "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers/");
    get.addHeader("Accept", "application/xml");
    HttpClient httpclient = new DefaultHttpClient();

    try {/*ww  w  .j av a  2 s . com*/
        HttpResponse response = httpclient.execute(get);
        assertEquals(200, response.getStatusLine().getStatusCode());
        // order returned can differ on OS so match for both orders
        String s = EntityUtils.toString(response.getEntity());
        assertNotNull(s);
        boolean m1 = s.endsWith(
                "<Customers><Customer><id>123</id><name>John</name></Customer><Customer><id>113</id><name>Dan</name></Customer></Customers>");
        boolean m2 = s.endsWith(
                "<Customers><Customer><id>113</id><name>Dan</name></Customer><Customer><id>123</id><name>John</name></Customer></Customers>");

        if (!m1 && !m2) {
            fail("Not expected body returned: " + s);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

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

@Test
public void testGetCustomers() throws Exception {
    HttpGet get = new HttpGet("http://localhost:9000/route/customerservice/customers/");
    get.addHeader("Accept", "application/xml");
    HttpClient httpclient = new DefaultHttpClient();

    try {/*w w  w . j a v  a2s  .co m*/
        HttpResponse response = httpclient.execute(get);
        assertEquals(200, response.getStatusLine().getStatusCode());
        // order returned can differ on OS so match for both orders
        String s = EntityUtils.toString(response.getEntity());
        assertNotNull(s);
        boolean m1 = s.endsWith(
                "<Customers><Customer><id>123</id><name>John</name></Customer><Customer><id>113</id><name>Dan</name></Customer></Customers>");
        boolean m2 = s.endsWith(
                "<Customers><Customer><id>113</id><name>Dan</name></Customer><Customer><id>123</id><name>John</name></Customer></Customers>");

        if (!m1 && !m2) {
            fail("Not expected body returned: " + s);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.linonly.livewallpaper.model.WOEIDUtils.java

private String fetchWOEIDxmlString(Context context, String queryString) {
    String qResult = "";

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpClient httpClient = new DefaultHttpClient(params);

    HttpGet httpGet = new HttpGet(queryString);

    try {//from ww w .  j  a v a 2s.  c om
        HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

        if (httpEntity != null) {
            InputStream inputStream = httpEntity.getContent();
            Reader in = new InputStreamReader(inputStream);
            BufferedReader bufferedreader = new BufferedReader(in);
            StringBuilder stringBuilder = new StringBuilder();

            String readLine = null;

            while ((readLine = bufferedreader.readLine()) != null) {
                stringBuilder.append(readLine + "\n");
            }

            qResult = stringBuilder.toString();
        }

    } catch (Exception e) {
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return qResult;
}