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:org.jenkinsci.plugins.stashNotifier.StashNotifier.java

/**
 * Notifies the configured Stash server by POSTing the build results 
 * to the Stash build API./*w  ww  .j av  a 2  s . c om*/
 * 
 * @param logger      the logger to use
 * @param build         the build to notify Stash of
 * @param commitSha1   the SHA1 of the built commit
 * @param client      the HTTP client with which to execute the request
 * @param listener      the build listener for logging
 * @param state         the state of the build as defined by the Stash API.
 */
private NotificationResult notifyStash(final PrintStream logger, final AbstractBuild<?, ?> build,
        final String commitSha1, final BuildListener listener, final StashBuildState state) throws Exception {
    HttpEntity stashBuildNotificationEntity = newStashBuildNotificationEntity(build, state);
    HttpPost req = createRequest(stashBuildNotificationEntity, commitSha1);
    HttpClient client = getHttpClient(logger);
    try {
        HttpResponse res = client.execute(req);
        if (res.getStatusLine().getStatusCode() != 204) {
            return NotificationResult.newFailure(EntityUtils.toString(res.getEntity()));
        } else {
            return NotificationResult.newSuccess();
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:ee.ioc.phon.netspeechapi.AudioUploader.java

private String postMultipartEntity(MultipartEntity entity) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost post = new HttpPost(mWsUrl);
    setUserAgent(post);//w  w  w .j  a  v a 2  s. c o m
    post.setEntity(entity);
    String responseAsString = "";

    try {
        HttpResponse response = client.execute(post);
        Header header = response.getFirstHeader(RESPONSE_HEADER_WEBTRANS_ID);
        if (header == null) {
            HttpEntity responseEntity = response.getEntity();
            responseAsString = EntityUtils.toString(responseEntity, HTTP.UTF_8);
        } else {
            // return the token
            responseAsString = header.getValue();
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
    return responseAsString;
}

From source file:org.neo4j.server.rest.ConfigureBaseUriDocIT.java

@Test
public void shouldUseRequestUriWhenNoXForwardHeadersPresent() throws Exception {
    URI rootUri = functionalTestHelper.baseUri();

    HttpClient httpclient = new DefaultHttpClient();
    try {/*  w w  w . j  a va 2 s. c  o m*/
        HttpGet httpget = new HttpGet(rootUri);

        httpget.setHeader("Accept", "application/json");

        HttpResponse response = httpclient.execute(httpget);

        String length = response.getHeaders("CONTENT-LENGTH")[0].getValue();
        byte[] data = new byte[Integer.valueOf(length)];
        response.getEntity().getContent().read(data);

        String responseEntityBody = new String(data);

        assertFalse(responseEntityBody.contains("https://foobar.com"));
        assertFalse(responseEntityBody.contains(":0"));
        assertTrue(responseEntityBody.contains("localhost"));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

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

/**
 * Tests if the modification date of a page can properly be adjusted by a
 * pagelet that is using the <code>&lt;modified&gt;</code> tag.
 * // w  ww. j  ava  2  s .c  om
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void testPageletModifcationDate(String serverUrl) throws Exception {
    logger.info("Preparing test of cache headers influenced by the 'modified' tag");

    // Load the page's modification date

    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages", modificationTestPageId);
    HttpGet getPageRequest = new HttpGet(requestUrl);
    HttpClient httpClient = new DefaultHttpClient();
    Page page = null;
    logger.info("Requesting the page's modification date at {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, getPageRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        PageReader reader = new PageReader();
        page = reader.read(response.getEntity().getContent(), site);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));

    // Regularly load the page

    requestUrl = UrlUtils.concat(serverUrl, modificationTestPage);

    logger.info("Sending request to {}", requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("X-Cache-Debug", "yes");
    String[][] params = new String[][] { {} };

    // Send and the request and examine the response. Keep the modification
    // date.
    httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, params);

        int statusCode = response.getStatusLine().getStatusCode();
        boolean okOrNotModified = statusCode == HttpServletResponse.SC_OK
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED;
        assertTrue(okOrNotModified);

        // Get the Modified header
        assertNotNull(response.getHeaders("Last-Modified"));
        assertEquals(1, response.getHeaders("Last-Modified").length);
        Date hostModified = df.parse(response.getHeaders("Last-Modified")[0].getValue());
        response.getEntity().consumeContent();

        // Make sure the page is advertised as being more recent than the page's
        // modification date
        assertTrue(hostModified.after(page.getModificationDate()));

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

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

/**
 * {@inheritDoc}//from ww w. j a va2 s .c om
 * 
 * @see ch.entwine.weblounge.testing.kernel.IntegrationTest#execute(java.lang.String)
 */
@Override
public void execute(String serverUrl) throws Exception {
    logger.info("Testing i18n dictionary and tag");

    String requestUrl = UrlUtils.concat(serverUrl, TEST_URL);
    HttpGet request = new HttpGet(requestUrl);
    logger.info("Sending request to {}", requestUrl);

    // Send and the request and examine the response
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        Document xml = TestUtils.parseXMLResponse(response);

        // Test i18n values defined at the module level
        String i18nModuleValue = "I18n Module Value";
        String xpath = "/html/body//div[@id='i18n-module']";
        Assert.assertEquals(i18nModuleValue, XPathHelper.valueOf(xml, xpath));

        // Test i18n values defined at the page level
        String i18nPageValue = "I18n Page Value";
        xpath = "/html/body//div[@id='i18n-page']";
        Assert.assertEquals(i18nPageValue, XPathHelper.valueOf(xml, xpath));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:id.nci.stm_9.HkpKeyServer.java

@Override
public void add(String armoredText) throws AddKeyException {
    HttpClient client = new DefaultHttpClient();
    try {//from   ww w  .  java  2  s. c o  m
        HttpPost post = new HttpPost("http://" + mHost + ":" + mPort + "/pks/add");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("keytext", armoredText));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new AddKeyException();
        }
    } catch (IOException e) {
        // nothing to do, better luck on the next keyserver
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.sociotech.communitymashup.source.readability.apiwrapper.ReadabilityAPIWrapper.java

@SuppressWarnings("unused")
private String doPost(String url, Map<String, String> parameterMap) {
    String result = null;/*from  ww  w . java 2s.c  om*/

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

    // add all post parameter
    for (String key : parameterMap.keySet()) {
        nameValuePairs.add(new BasicNameValuePair(key, parameterMap.get(key)));
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        result = httpClient.execute(post, responseHandler);
    } catch (Exception e) {
        // do nothing
    } finally {
        // client is no longer needed
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:com.nostra13.example.universalimageloader.HomeActivity.java

private void getJson() {
    try {/*ww w. ja  v  a2  s.co  m*/
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);

        //prepare the HTTP GET call
        HttpGet httpget = new HttpGet("http://www.moncl.net:8888/stores.json");

        //get the response
        HttpEntity entity = httpClient.execute(httpget).getEntity();

        if (entity != null) {
            //get the response content as a string
            String response = EntityUtils.toString(entity);
            Log.d("Hello", response);
            //consume the entity
            entity.consumeContent();

            // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();

            jsonArray = new JSONArray(response);

        }
    } catch (Exception e) {
        e.printStackTrace();
        String error = e.toString();
        Log.d("Hello", error);
    }
}

From source file:io.werval.gradle.ApplicationPluginIntegTest.java

@Test
public void startTaskIntegrationTest() throws InterruptedException, IOException {
    final Holder<Exception> errorHolder = new Holder<>();
    Thread runThread = new Thread(newRunnable(errorHolder, "start"), "gradle-werval-start-thread");
    try {/*w w w  . ja v  a 2 s  . c  om*/
        runThread.start();

        final HttpClient client = new DefaultHttpClient();
        final HttpGet get = new HttpGet("http://localhost:23023/");
        final ResponseHandler<String> handler = new BasicResponseHandler();

        await().atMost(60, SECONDS).pollInterval(5, SECONDS).until(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    return client.execute(get, handler);
                } catch (Exception ex) {
                    return null;
                }
            }
        }, allOf(containsString("I ran!"), containsString("custom")));

        client.getConnectionManager().shutdown();

        if (errorHolder.isSet()) {
            throw new RuntimeException(
                    "Error during werval:start invocation: " + errorHolder.get().getMessage(),
                    errorHolder.get());
        }
    } finally {
        runThread.interrupt();
    }
}

From source file:com.nostra13.example.universalimageloader.HomeActivity.java

private void getTabStringJSON() {
    try {/* w ww  . ja v a 2  s  . c  o  m*/
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);

        //prepare the HTTP GET call
        HttpGet httpget = new HttpGet("http://moncl.net:8888/categories.json");

        //get the response
        HttpEntity entity = httpClient.execute(httpget).getEntity();

        if (entity != null) {
            //get the response content as a string
            String response = EntityUtils.toString(entity);
            Log.d("Hello", response);
            //consume the entity
            entity.consumeContent();

            // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();

            JSONArray jsonArray = new JSONArray(response);

            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject object1 = (JSONObject) jsonArray.get(i);
                    String nameString = object1.getString("name");
                    Log.d("", nameString);
                    tmp_TabStringArray.add(nameString);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        String error = e.toString();
        Log.d("Hello", error);
    }
}