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

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

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:ch.ralscha.extdirectspring_itest.InfoServiceTest.java

@SuppressWarnings("unchecked")
private static void testInfoPost(String method) throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {//from   w w  w . j a v a 2 s .  com
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("extTID", "1"));
        formparams.add(new BasicNameValuePair("extAction", "infoService"));
        formparams.add(new BasicNameValuePair("extMethod", method));
        formparams.add(new BasicNameValuePair("extType", "rpc"));
        formparams.add(new BasicNameValuePair("extUpload", "false"));
        formparams.add(new BasicNameValuePair("userName", "RALPH"));
        UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

        post.setEntity(postEntity);

        response = client.execute(post);
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(responseString, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo(method);
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("infoService");
        assertThat(rootAsMap.get("tid")).isEqualTo(1);

        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(2);
        assertThat(result.get("user-name-lower-case")).isEqualTo("ralph");
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:no.kantega.commons.taglib.util.GetHtmlTag.java

public int doStartTag() throws JspException {
    HttpGet get = new HttpGet(url);
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    get.setHeader("User-Agent", request.getHeader("User-Agent"));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try (CloseableHttpResponse response = httpclient.execute(get)) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            pageContext.getOut().write(IOUtils.toString(entity.getContent()));
        }/*from ww  w.  ja  v  a  2s.c  o  m*/
    } catch (IOException e) {
        log.error("Error getting html", e);
    }
    return SKIP_BODY;
}

From source file:org.squashtest.tm.plugin.testautomation.jenkins.internal.net.RequestExecutor.java

public String execute(CloseableHttpClient client, HttpUriRequest method) {
    try (CloseableHttpResponse resp = client.execute(method)) {
        checkResponseCode(resp.getStatusLine());

        ResponseHandler<String> handler = new BasicResponseHandler();

        return handler.handleResponse(resp);
    } catch (AccessDenied ex) {
        throw new AccessDenied(
                "Test automation - jenkins : operation rejected the operation because of wrong credentials"); // NOSONAR no need for actual call stack
    } catch (IOException ex) {
        throw new ServerConnectionFailed(
                "Test automation - jenkins : could not connect to server due to technical error : ", ex);
    }/*w  w w.  j a va  2 s . co m*/
}

From source file:ar.com.colo.rest.test.RestletTestSupport.java

public HttpResponse doExecute(HttpUriRequest method) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {/*from w ww .  j a va  2  s .c om*/
        HttpResponse response = client.execute(method);
        response.setEntity(new BufferedHttpEntity(response.getEntity()));
        return response;
    } finally {
        client.close();
    }
}

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

protected static void add() throws Exception {
    ITVenueController.add();/*  www .j  a  va 2 s.co m*/
    ITHiredJudgeController.add();
    ITJudgeController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getPeople().add(TestFixture.INSTANCE.andy);
    doc.getPeople().add(TestFixture.INSTANCE.jamie);
    doc.getPeople().add(TestFixture.INSTANCE.bob);
    doc.getPeople().add(TestFixture.INSTANCE.eoin);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeAndy);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeJamie);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeBob);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeEoin);
    doc.getSoloContests().add(TestFixture.INSTANCE.soloContest);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

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

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

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

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.soloContest.setId(doc.getSoloContests().get(0).getId());

        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);
            }
        }
    }

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

    httpPost = new HttpPost(uri);

    xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        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);
            }
        }
    }

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

    httpPost = new HttpPost(uri);

    xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

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

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.soloContest.setId(doc.getSoloContests().get(0).getId());

        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);
            }
        }
    }
}

From source file:org.commonjava.indy.ftest.core.urls.StoreOneAndSourceStoreUrlInHtmlListingTest.java

@Test
public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception {
    final byte[] data = "this is a test".getBytes();
    final ByteArrayInputStream stream = new ByteArrayInputStream(data);
    final String root = "/path/to/";
    final String path = root + "foo.txt";

    client.content().store(hosted, STORE, path, stream);

    final IndyClientHttp http = getHttp();

    final HttpGet request = http.newRawGet(client.content().contentUrl(hosted, STORE, root));

    request.addHeader("Accept", "text/html");

    final CloseableHttpClient hc = http.newClient();
    final CloseableHttpResponse response = hc.execute(request);

    final InputStream listing = response.getEntity().getContent();
    final String html = IOUtils.toString(listing);

    // TODO: Charset!!
    final Document doc = Jsoup.parse(html);
    for (final Element item : doc.select("a.source-link")) {
        final String fname = item.text();
        System.out.printf("Listing contains: '%s'\n", fname);
        final String href = item.attr("href");
        final String expected = client.content().contentUrl(hosted, STORE);

        assertThat(fname + " does not have a href", href, notNullValue());
        assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName()
                + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected));
    }/*from w  w w  .  j a  v a2  s  .  com*/
}

From source file:org.commonjava.indy.ftest.core.urls.StoreOneAndVerifyInHtmlListingTest.java

@Test
public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception {
    final byte[] data = "this is a test".getBytes();
    final ByteArrayInputStream stream = new ByteArrayInputStream(data);
    final String root = "/path/to/";
    final String path = root + "foo.txt";

    client.content().store(hosted, STORE, path, stream);

    final IndyClientHttp http = getHttp();

    final HttpGet request = http.newRawGet(client.content().contentUrl(hosted, STORE, root));

    request.addHeader("Accept", "text/html");

    final CloseableHttpClient hc = http.newClient();
    final CloseableHttpResponse response = hc.execute(request);

    final InputStream listing = response.getEntity().getContent();
    final String html = IOUtils.toString(listing);

    // TODO: Charset!!
    final Document doc = Jsoup.parse(html);
    for (final Element item : doc.select("a.item-link")) {
        final String fname = item.text();
        System.out.printf("Listing contains: '%s'\n", fname);
        final String href = item.attr("href");
        final String expected = client.content().contentUrl(hosted, STORE, root, fname);

        assertThat(fname + " does not have a href", href, notNullValue());
        assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName()
                + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected));
    }//  w  w w .  j  av  a 2s  .  c o m
}

From source file:org.duracloud.duradmin.integration.selenium.HomeTest.java

public void testForFavicon() throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(getBaseURL() + "favicon.ico");
    HttpResponse response = client.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertTrue(response.getHeaders("Content-Type").length == 0);
}

From source file:org.commonjava.aprox.folo.ftest.urls.StoreOneAndSourceStoreUrlInHtmlListingTest.java

@Test
public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception {
    final byte[] data = "this is a test".getBytes();
    final ByteArrayInputStream stream = new ByteArrayInputStream(data);
    final String root = "/path/to/";
    final String path = root + "foo.txt";
    final String track = "track";

    content.store(track, hosted, STORE, path, stream);

    final AproxClientHttp http = getHttp();

    final HttpGet request = http.newRawGet(content.contentUrl(track, hosted, STORE, root));

    request.addHeader("Accept", "text/html");

    final CloseableHttpClient hc = http.newClient();
    final CloseableHttpResponse response = hc.execute(request);

    final InputStream listing = response.getEntity().getContent();
    final String html = IOUtils.toString(listing);

    // TODO: Charset!!
    final Document doc = Jsoup.parse(html);
    for (final Element item : doc.select("a.source-link")) {
        final String fname = item.text();
        System.out.printf("Listing contains: '%s'\n", fname);
        final String href = item.attr("href");
        final String expected = client.content().contentUrl(hosted, STORE);

        assertThat(fname + " does not have a href", href, notNullValue());
        assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName()
                + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected));
    }// w w w  .  j  a v  a  2 s .  c o m
}

From source file:org.commonjava.aprox.folo.ftest.urls.StoreOneAndVerifyInHtmlListingTest.java

@Test
public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception {
    final byte[] data = "this is a test".getBytes();
    final ByteArrayInputStream stream = new ByteArrayInputStream(data);
    final String root = "/path/to/";
    final String path = root + "foo.txt";
    final String track = "track";

    content.store(track, hosted, STORE, path, stream);

    final AproxClientHttp http = getHttp();

    final HttpGet request = http.newRawGet(content.contentUrl(track, hosted, STORE, root));

    request.addHeader("Accept", "text/html");

    final CloseableHttpClient hc = http.newClient();
    final CloseableHttpResponse response = hc.execute(request);

    final InputStream listing = response.getEntity().getContent();
    final String html = IOUtils.toString(listing);

    // TODO: Charset!!
    final Document doc = Jsoup.parse(html);
    for (final Element item : doc.select("a.item-link")) {
        final String fname = item.text();
        System.out.printf("Listing contains: '%s'\n", fname);
        final String href = item.attr("href");
        final String expected = client.content().contentUrl(hosted, STORE, root, fname);

        assertThat(fname + " does not have a href", href, notNullValue());
        assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName()
                + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected));
    }/*from   ww w . java 2 s . com*/
}