Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:com.bbc.util.ClientCustomSSL.java

public static String clientCustomSLL(String mchid, String path, String data) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    System.out.println("?...");
    FileInputStream instream = new FileInputStream(new File("/payment/apiclient_cert.p12"));
    try {//from  ww  w  . j  av a2  s .c o  m
        keyStore.load(instream, mchid.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httpost = new HttpPost(path);
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer("");
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                    sb.append(text);
                }
                return sb.toString();

            }
            EntityUtils.consume(entity);
            return "";
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:net.officefloor.plugin.woof.WoofOfficeFloorSourceTest.java

/**
 * Ensure unit test methods appropriately start and stop.
 */// w  w  w. j  ava 2s .  c o m
public void testUnitTestMethods() throws Exception {

    final String connectionMessageSuffix = "failed: Connection refused";

    // Should not successfully connect
    try {
        this.doRequest("/test");
        fail("Should not be successful");
    } catch (HttpHostConnectException ex) {
        assertTrue("Incorrect cause: " + ex.getMessage(), ex.getMessage().endsWith(connectionMessageSuffix));
    }

    // Run the application
    WoofOfficeFloorSource.start();

    // Should now be running
    this.doTestRequest("/test");

    // Stop the application
    WoofOfficeFloorSource.stop();

    // Should not successfully connect
    CloseableHttpClient refreshedClient = HttpTestUtil.createHttpClient();
    try {
        refreshedClient.execute(new HttpGet("http://localhost:7878/test"));
        fail("Should not be successful");
    } catch (HttpHostConnectException ex) {
        assertTrue("Incorrect cause: " + ex.getMessage(), ex.getMessage().endsWith(connectionMessageSuffix));
    } finally {
        refreshedClient.close();
    }
}

From source file:com.navercorp.pinpoint.plugin.httpclient4.CloaeableHttpClientIT.java

@Test
public void test() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from  w  w  w  .j ava 2s  .co m
        HttpGet httpget = new HttpGet("http://www.naver.com");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                } catch (IOException ex) {
                    throw ex;
                } finally {
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            CloseableHttpClient.class.getMethod("execute", HttpUriRequest.class)));
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            PoolingHttpClientConnectionManager.class.getMethod("connect", HttpClientConnection.class,
                    HttpRoute.class, int.class, HttpContext.class),
            annotation("http.internal.display", "www.naver.com:80")));
    verifier.verifyTrace(event("HTTP_CLIENT_4",
            HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class,
                    HttpContext.class),
            null, null, "www.naver.com", annotation("http.url", "/"), annotation("http.status.code", 200),
            annotation("http.io", anyAnnotationValue())));
    verifier.verifyTraceCount(0);
}

From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java

private AlfrescoResponse getDocumentsActions(String url) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    logger.debug("Hitting url: {}", url);

    try {// www.  ja  va  2s  . c  om
        HttpGet httpGet = createGetRequest(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        AlfrescoResponse afResponse = fromHttpEntity(entity);
        EntityUtils.consume(entity);
        response.close();
        httpClient.close();
        return afResponse;
    } catch (IOException e) {
        logger.warn("Failed to fetch nodes.", e);
        throw new AlfrescoDownException("Alfresco appears to be down", e);
    }
}

From source file:org.keycloak.test.FluentTestsHelper.java

/**
 * Checks if a given endpoint returns Forbidden HTTP Code.
 *
 * @param endpoint Endpoint to be evaluated,
 * @return <code>true</code> if the endpoint returns forbidden.
 * @throws IOException Thrown by the underlying HTTP Client implementation
 *//*from w  w w . ja  v a2  s  .co  m*/
public boolean returnsForbidden(String endpoint) throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpGet get = new HttpGet(keycloakBaseUrl + endpoint);
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == 403
                || response.getStatusLine().getStatusCode() == 401) {
            return true;
        } else {
            return false;
        }

    } finally {
        client.close();
    }
}

From source file:org.apache.hive.service.server.TestHS2HttpServerPam.java

@Test
public void testAuthorizedConnection() throws Exception {
    CloseableHttpClient httpclient = null;
    try {/*from  w w w  . j a v  a 2  s .c  o m*/
        String username = "user1";
        String password = "1";
        httpclient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet("http://" + host + ":" + webUIPort);
        String authB64Code = B64Code.encode(username + ":" + password, StringUtil.__ISO_8859_1);
        httpGet.setHeader(HttpHeader.AUTHORIZATION.asString(), "Basic " + authB64Code);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        Assert.assertTrue(response.toString().contains(Integer.toString(HttpURLConnection.HTTP_OK)));

    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:com.restfiddle.handler.http.GenericHandler.java

/**
 * This method will be used for API processing and the method below this will be deprecated.
 *///from  ww w .jav  a 2  s  .c  o  m
public RfResponseDTO processHttpRequest(RfRequestDTO rfRequestDTO) {
    HttpUriRequest httpUriRequest = rfRequestBuilder.build(rfRequestDTO);

    CloseableHttpClient httpClient = rfHttpClientBuilder.build(rfRequestDTO, httpUriRequest);

    RfResponseDTO responseDTO = null;
    try {
        long startTime = System.currentTimeMillis();
        CloseableHttpResponse httpResponse = httpClient.execute(httpUriRequest);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        responseDTO = buildRfResponse(httpResponse, duration, rfRequestDTO);
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return responseDTO;
}

From source file:org.apache.hive.service.server.TestHS2HttpServerPam.java

@Test
public void testIncorrectPassword() throws Exception {
    CloseableHttpClient httpclient = null;
    try {/*  w  ww  .ja  va 2s .  c o m*/
        String username = "user1";
        String password = "aaaa";
        httpclient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet("http://" + host + ":" + webUIPort);
        String authB64Code = B64Code.encode(username + ":" + password, StringUtil.__ISO_8859_1);
        httpGet.setHeader(HttpHeader.AUTHORIZATION.asString(), "Basic " + authB64Code);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        Assert.assertTrue(response.toString().contains(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));

    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:org.apache.hive.service.server.TestHS2HttpServerPam.java

@Test
public void testIncorrectUser() throws Exception {
    CloseableHttpClient httpclient = null;
    try {//from  w  ww.j  a va 2 s. c  o m
        String username = "nouser";
        String password = "aaaa";
        httpclient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet("http://" + host + ":" + webUIPort);
        String authB64Code = B64Code.encode(username + ":" + password, StringUtil.__ISO_8859_1);
        httpGet.setHeader(HttpHeader.AUTHORIZATION.asString(), "Basic " + authB64Code);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        Assert.assertTrue(response.toString().contains(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));

    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java

private void recordTest(String jobId, String data, int retry) {
    String remotewebdriver = System.getProperty("org.callimachusproject.test.remotewebdriver");
    if (remotewebdriver != null && remotewebdriver.contains("saucelabs.com")) {
        URI uri = URI.create(remotewebdriver);
        CloseableHttpClient client = HttpClientBuilder.create().useSystemProperties()
                .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build()).build();
        try {// w ww .j a  v  a 2s .c  om
            try {
                String info = uri.getUserInfo();
                putTestData(info, jobId, data, client);
            } finally {
                client.close();
            }
        } catch (IOException ex) {
            if (retry > 0) {
                logger.warn(ex.toString(), ex);
                recordTest(jobId, data, retry - 1);
            } else {
                logger.error(ex.toString(), ex);
            }
        } catch (RuntimeException ex) {
            logger.error(ex.toString(), ex);
        }
    }
}