Example usage for org.apache.http.util EntityUtils consume

List of usage examples for org.apache.http.util EntityUtils consume

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils consume.

Prototype

public static void consume(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:guru.nidi.loader.url.FormLoginUrlFetcher.java

@Override
public InputStream fetchFromUrl(CloseableHttpClient client, String base, String name, long ifModifiedSince) {
    try {/*from   w ww. j a  va 2 s . c om*/
        final HttpPost login = new HttpPost(base + "/" + loginUrl);
        final List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(loginField, this.login));
        params.add(new BasicNameValuePair(passwordField, password));
        postProcessLoginParameters(params);
        login.setEntity(new UrlEncodedFormEntity(params));
        try (final CloseableHttpResponse getResult = client.execute(postProcessLogin(login))) {
            if (getResult.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw new Loader.ResourceNotFoundException(name,
                        "Could not login: " + getResult.getStatusLine().toString());
            }
            EntityUtils.consume(getResult.getEntity());
        }
        return super.fetchFromUrl(client, base + "/" + loadPath, name, ifModifiedSince);
    } catch (IOException e) {
        throw new Loader.ResourceNotFoundException(name, e);
    }
}

From source file:com.intel.cosbench.client.swauth.SwiftAuthClient.java

public void login() throws IOException, SwiftAuthClientException {
    HttpResponse response = null;//  w w w . j  a  v a  2  s  .co m
    try {
        HttpGet method = new HttpGet(authURL);
        method.setHeader(X_STORAGE_USER, username);
        method.setHeader(X_STORAGE_PASS, password);
        response = client.execute(method);
        if ((response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK)
                && (response.getStatusLine().getStatusCode() < (HttpStatus.SC_OK + 100))) {
            authToken = response.getFirstHeader(X_AUTH_TOKEN) != null
                    ? response.getFirstHeader(X_AUTH_TOKEN).getValue()
                    : null;
            storageURL = response.getFirstHeader(X_STORAGE_URL) != null
                    ? response.getFirstHeader(X_STORAGE_URL).getValue()
                    : null;
            return;
        }
        throw new SwiftAuthClientException(response.getStatusLine().getStatusCode(),
                response.getStatusLine().getReasonPhrase());
    } finally {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    }
}

From source file:org.piraso.client.net.HttpPirasoStartHandler.java

public void execute() throws IOException, SAXException, ParserConfigurationException {
    try {/* w w  w  .  j av  a  2 s.  co  m*/
        doExecute();
    } finally {
        complete = true;
        EntityUtils.consume(responseEntity);
    }
}

From source file:org.gitana.platform.client.ApplicationDeploymentTest.java

@Test
public void testDeployments() throws Exception {
    Gitana gitana = new Gitana();

    // authenticate
    Platform platform = gitana.authenticate("admin", "admin");

    // create a web host
    WebHost webhost = platform.createWebHost();
    webhost.setDeployerTypes(Arrays.asList("dev-cloudcms.net", "cloudcms.net"));
    webhost.update();//from   w  ww.ja v  a 2s  .co  m

    // create an application
    Application application = platform.createApplication();
    //application.addDeployment("test", webhost.getId(), "gitana-build-test-" + System.currentTimeMillis(), "dev-cloudcms.net", JSONBuilder.start("test").is(true).get());
    //application.setSource("github", true, "https://github.com/gitana/app-html5-test.git");
    application.addDeployment("test", webhost.getId(), "gitana-build-test-" + System.currentTimeMillis(),
            "cloudcms.net", JSONBuilder.start("test").is(true).get());
    application.setSource("github", true, "https://github.com/solocal/hplace.git");
    application.update();

    // deploy the application
    DeployedApplication deployedApplication = application.deploy("test");
    String url = deployedApplication.getUrls().get(0);

    // load to verify it's up
    HttpResponse response = HttpUtilEx.get(HttpUtil.buildClient(), url);
    assertEquals(200, response.getStatusLine().getStatusCode());

    // consume
    EntityUtils.consume(response.getEntity());

    // now undeploy
    deployedApplication.undeploy();
}

From source file:com.github.restdriver.clientdriver.integration.BodyCaptureTest.java

@Test
public void canCaptureRequestBodyAsJson() throws Exception {

    JsonBodyCapture capture = new JsonBodyCapture();

    clientDriver.addExpectation(onRequestTo("/foo").withMethod(Method.POST).capturingBodyIn(capture),
            giveEmptyResponse().withStatus(201));

    HttpClient client = new DefaultHttpClient();
    HttpPost correctPost = new HttpPost(clientDriver.getBaseUrl() + "/foo");
    correctPost.setEntity(new StringEntity("{\"a\": \"A\"}"));
    HttpResponse correctResponse = client.execute(correctPost);
    EntityUtils.consume(correctResponse.getEntity());

    assertThat(capture.getContent(), hasJsonPath("$.a", equalTo("A")));
}

From source file:com.signicat.hystrix.servlet.AsyncWrapperServletTest.java

@Test
public void require_That_Servlet_Timeout_Kicks_In_But_Hystrix_Timeout_Does_Not_Kick_In() throws Exception {
    CountDownLatch servletTimeout = new CountDownLatch(1);

    final AsyncTestServlet servlet = new AsyncTestServlet(new CountDownLatch(1), servletTimeout,
            new CountDownLatch(1), new CountDownLatch(1), new CountDownLatch(1), new CountDownLatch(1), null,
            new TimeoutServlet(servletTimeout), 1000L);
    try (TestServer server = new TestServer(0, servlet)) {
        server.start();/*from  ww  w . j a  va 2 s  . c om*/
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet("http://localhost:" + server.getPort() + "/bananarama");
            try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) {
                StatusLine statusLine = httpResponse.getStatusLine();
                assertThat(statusLine.getStatusCode(), equalTo(504));
                assertThat(statusLine.getReasonPhrase(), equalTo("Timeout from async listener"));
                EntityUtils.consume(httpResponse.getEntity());
                assertThat(servlet.servletTimeout.await(60, TimeUnit.SECONDS), is(true));
                assertThat(servlet.servletComplete.await(60, TimeUnit.SECONDS), is(true));
                assertThat(servlet.servletError.getCount(), equalTo(1L));
                assertThat(servlet.hystrixError.await(60, TimeUnit.SECONDS), is(true));
                assertThat(servlet.hystrixCompleted.getCount(), equalTo(1L));
                assertThat(servlet.hystrixNext.getCount(), equalTo(1L));
            }
        }
    }
}

From source file:eu.seaclouds.platform.planner.core.utils.HttpHelper.java

/**
 * @param restPath/*from   ww w  . j av a 2 s.  com*/
 * @param params
 * @return
 */
public String getRequest(String restPath, List<NameValuePair> params) {
    log.info("Getting request for " + this.serviceURL + restPath);

    HttpGet httpGet = new HttpGet(prepareRequestURL(restPath, params));
    CloseableHttpResponse response = null;
    String content = "";
    try {
        response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        content = new Scanner(entity.getContent()).useDelimiter("\\Z").next();
        EntityUtils.consume(entity);
        log.info("Request executed succesfully");
    } catch (IOException e) {
        log.error("IOException", e);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            log.error("IOEXception", e);
        }
    }
    return content;
}

From source file:groovesquid.GetAdsThread.java

public static String getFile(String url) {
    String responseContent = null;
    HttpEntity httpEntity = null;//from   w ww .  j a  va2s  . c  o  m
    try {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        httpGet.setHeader(HTTP.USER_AGENT,
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse httpResponse = httpClient.execute(httpGet);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        httpEntity = httpResponse.getEntity();

        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity.writeTo(baos);
        } else {
            throw new RuntimeException(url);
        }

        responseContent = baos.toString("UTF-8");
    } catch (Exception ex) {
        log.log(Level.SEVERE, null, ex);
    } finally {
        try {
            EntityUtils.consume(httpEntity);
        } catch (IOException ex) {
            log.log(Level.SEVERE, null, ex);
        }
    }
    return responseContent;
}

From source file:com.kurento.test.player.PlayerTst.java

@Override
public void run() {
    try {// w w  w . ja v a 2s .co  m
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity resEntity = response.getEntity();

        if (interrupt) {
            // Interrupt test
            resEntity.getContent().close();
        } else if (contentType != null) {
            // If not reject test
            final long initTime = new Date().getTime();
            EntityUtils.consume(resEntity);
            final long seconds = (new Date().getTime() - initTime) / 1000 % 60;
            log.info("Play time: " + seconds + " seconds");
        }

        final int responseStatusCode = response.getStatusLine().getStatusCode();
        log.info("ReasonPhrase " + response.getStatusLine().getReasonPhrase());
        log.info("statusCode " + responseStatusCode);
        Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode);

        if (expectedHandlerFlow != null) {
            final List<String> realEventList = EventListener.getEventList();
            log.info("Real Event List: " + realEventList);
            Assert.assertArrayEquals(expectedHandlerFlow, realEventList.toArray());
        }

        if (contentType != null && resEntity.getContentType() != null) {
            Header responseContentType = resEntity.getContentType();
            log.info("contentType " + responseContentType.getValue());
            Assert.assertEquals("Content-Type in response header must be " + contentType, contentType,
                    responseContentType.getValue());
        }

    } catch (Exception e) {
        log.error("Exception in Player Test", e);
    }
}

From source file:com.intel.cosbench.controller.tasklet.AbstractHttpTasklet.java

private static String fetchResponseBody(HttpResponse response) throws IOException {
    String body = null;//w  ww.j ava  2  s. c  o  m
    HttpEntity entity = response.getEntity();
    StatusLine status = response.getStatusLine();
    try {
        body = EntityUtils.toString(entity);
    } finally {
        EntityUtils.consume(entity);
    }
    if (body.length() < 2048)
        LOGGER.debug("[ << ] - {} {}", status, body);
    else
        LOGGER.debug("[ << ] - {} [body-omitted]", status);
    return body; // the response body
}