Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse 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.abc.turkey.service.unfreeze.SmsService.java

public void sendSms(String smsCode) throws Exception {
    String did = getNextDid();//  www . j ava2s  .  co m
    String content = "{\"code\":\"" + smsCode + "\"}";
    content = URLEncoder.encode(content, "utf-8");
    String sendUrl = "http://www.7tds.com/api/order/send?&did=" + did + "&inputs=" + content;
    HttpGet httpGet = new HttpGet(sendUrl);
    CloseableHttpResponse response = httpclient.execute(httpGet);
    String res = EntityUtils.toString(response.getEntity(), "utf8");
    response.close();
    logger.debug(res);
    checkRes(res, httpGet);
}

From source file:org.wuspba.ctams.ws.ITRosterController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (Roster r : doc.getRosters()) {
            ids.add(r.getId());//from   w w w.  ja va 2 s .co m
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }

    ITBandRegistrationController.delete();
    ITBandMemberController.delete();
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslServices() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();//  ww w .  j a  va  2 s. com

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // HTTPS client - with
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    jqmlogger.debug(rq.getURI());
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:org.apache.camel.component.hipchat.HipchatProducer.java

protected StatusLine post(String urlPath, Map<String, String> postParam) throws IOException {
    HttpPost httpPost = new HttpPost(getConfig().hipChatUrl() + urlPath);
    httpPost.setEntity(new StringEntity(MAPPER.writeValueAsString(postParam), ContentType.APPLICATION_JSON));
    CloseableHttpResponse closeableHttpResponse = HTTP_CLIENT.execute(httpPost);
    try {/*from   w ww.  j  a  v a  2  s . c o  m*/
        return closeableHttpResponse.getStatusLine();
    } finally {
        closeableHttpResponse.close();
    }
}

From source file:com.abc.turkey.service.unfreeze.UnfreezeProxy.java

private int checkState2(String randstr) throws Exception {
    // ?/*ww w  .j  ava2  s.c  om*/
    String lockUrl = "https://aq.qq.com/cn2/login_limit/checkstate?from=2&verifycode=" + randstr;
    HttpGet httpGet = new HttpGet(lockUrl);
    CloseableHttpResponse response = httpclient.execute(httpGet);
    String res = EntityUtils.toString(response.getEntity(), "utf8");
    logger.debug(res);
    response.close();
    return JSON.parseObject(res).getIntValue("if_lock");
}

From source file:org.jenkinsci.plugins.kubernetesworkflowsteps.KubeStepExecution.java

protected Object parse(CloseableHttpResponse resp) throws IOException {
    try {//from   ww  w . ja  va 2 s .c o m
        return (new JsonSlurper()).parse((new InputStreamReader(resp.getEntity().getContent())));
    } finally {
        resp.close();
    }

}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException {

    final InputStream inputStream;

    if (response.getEntity() == null) {
        inputStream = new ByteArrayInputStream(new byte[0]);
    } else {/*from  w  w  w.  j a  va  2s .c om*/
        final InputStream i = response.getEntity().getContent();
        if (i.markSupported()) {
            inputStream = i;
        } else {
            inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
        }
    }

    return new FilterInputStream(inputStream) {
        @Override
        public void close() throws IOException {
            response.close();
            super.close();
        }
    };
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslClientCert() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();/*from w  ww.  jav a  2  s .  co m*/

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // Server auth against trusted CA root certificate
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    // Client auth
    JpaCa.prepareClientStore(em, "CN=testuser", "./conf/client.pfx", "SuperPassword", "client-cert",
            "./conf/client.cer");
    KeyStore clientStore = KeyStore.getInstance("PKCS12");
    instream = new FileInputStream(new File("./conf/client.pfx"));
    try {
        clientStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore)
            .loadKeyMaterial(clientStore, "SuperPassword".toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:org.wildfly.test.integration.microprofile.health.MicroProfileHealthSecuredHTTPEndpointEmptyMgmtUsersTestCase.java

@Test
public void securedHTTPEndpointWithoutUserDefined() throws Exception {
    final String healthURL = "http://" + managementClient.getMgmtAddress() + ":"
            + managementClient.getMgmtPort() + "/health";

    try (CloseableHttpClient client = HttpClients.createDefault()) {
        CloseableHttpResponse resp = client.execute(new HttpGet(healthURL));
        assertEquals(500, resp.getStatusLine().getStatusCode());
        String content = MicroProfileHealthHTTPEndpointTestCase.getContent(resp);
        resp.close();
        assertTrue("'WFLYDMHTTP0016: Your Application Server is running. However ...' message is expected",
                content.contains("WFLYDMHTTP0016"));
    }/*from  w w  w.ja va  2s .c o  m*/
}

From source file:myexamples.MyExamples.java

public static void getExample() throws IOException {
    HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {//  ww  w.ja  v  a 2  s.c  om
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        if (entity1 != null) {
            long len = entity1.getContentLength();
            if (len != -1 && len < 2048) {
                System.out.println(EntityUtils.toString(entity1));
            } else {
                System.out.println("entity length=" + len);
            }
        }

        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
}