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:org.jboss.as.test.integration.web.security.form.AbstractWebSecurityFORMTestCase.java

/**
 * Makes a HTTP request to the protected web application.
 * /*from   w ww.java  2  s  .  co m*/
 * @param user
 * @param pass
 * @param expectedStatusCode
 * @throws Exception
 * @see org.jboss.as.test.integration.web.security.WebSecurityPasswordBasedBase#makeCall(java.lang.String, java.lang.String,
 *      int)
 */
@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        String req = url.toExternalForm() + "secured/";
        HttpGet httpget = new HttpGet(req);

        HttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        // We should get the Login Page
        StatusLine statusLine = response.getStatusLine();
        LOGGER.info("Login form get: " + statusLine);
        assertEquals(200, statusLine.getStatusCode());

        LOGGER.info("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            LOGGER.info("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                LOGGER.info("- " + cookies.get(i).toString());
            }
        }
        req = url.toExternalForm() + "secured/j_security_check";
        // We should now login with the user name and password
        HttpPost httpPost = new HttpPost(req);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", user));
        nvps.add(new BasicNameValuePair("j_password", pass));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpPost);
        entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        statusLine = response.getStatusLine();

        // Post authentication - we have a 302
        assertEquals(302, statusLine.getStatusCode());
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();

        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);

        entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        LOGGER.info("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            LOGGER.info("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                LOGGER.info("- " + cookies.get(i).toString());
            }
        }

        // Either the authentication passed or failed based on the expected status code
        statusLine = response.getStatusLine();
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.wso2.developerstudio.appfactory.core.client.RssClient.java

public static String getDBinfo(String operation, String dsBaseUrl) {
    String url = dsBaseUrl + "NDataSourceAdmin";
    DefaultHttpClient client = new DefaultHttpClient();
    client = (DefaultHttpClient) HttpsJaggeryClient.wrapClient(client, url);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Authenticator.getInstance().getCredentials().getUser(),
                    Authenticator.getInstance().getCredentials().getPassword()));

    // Generate BASIC scheme object and stick it to the execution context
    BasicScheme basicAuth = new BasicScheme();
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpPost post = new HttpPost(url);
    String sopactionValue = "urn:" + operation;
    post.addHeader("SOAPAction", sopactionValue);
    String body = createPayLoad(operation);
    try {/*from  w w w .j  a v a2s  .  c o m*/
        StringEntity entity = new StringEntity(body.toString(), "text/xml", HTTP.DEFAULT_CONTENT_CHARSET);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            HttpEntity entityGetAppsOfUser = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            String respond = sb.toString();
            EntityUtils.consume(entityGetAppsOfUser);
            return respond;
        }
    } catch (Exception e) {
        // log.error("Jenkins Client err", e);
    }
    return null;
}

From source file:com.github.parisoft.resty.entity.EntityReaderImpl.java

@Override
public <T> T getEntityAs(Class<T> someClass) throws IOException {
    if (body != null) {
        return getEntityFromBodyAs(someClass);
    }/*  www .  j a v a2  s. c  om*/

    final HttpEntity entity = httpResponse.getEntity();

    if (entity == null) {
        return null;
    }

    try {
        final HttpEntity entityWrapper = isGzipEncoding() ? new GzipDecompressingEntity(entity) : entity;

        return JacksonUtils.read(entityWrapper, someClass, MediaTypeUtils.valueOf(getContentType()));
    } catch (Exception e) {
        if (isInstanciableFromString(someClass)) {
            return newInstanceFromString(someClass, getEntityAsString());
        }

        throw new IOException("Cannot read response entity", e);
    } finally {
        EntityUtils.consume(entity);
    }
}

From source file:org.gradle.internal.resource.transport.http.HttpClientHelper.java

protected HttpResponse executeGetOrHead(HttpRequestBase method) throws IOException {
    HttpResponse httpResponse = performHttpRequest(method);
    // Consume content for non-successful, responses. This avoids the connection being left open.
    if (!wasSuccessful(httpResponse)) {
        EntityUtils.consume(httpResponse.getEntity());
        return httpResponse;
    }/*w ww.j  a va2  s  . co  m*/
    return httpResponse;
}

From source file:com.apm4all.tracy.TracyAsyncHttpClientPublisher.java

private String extractPostResponse(HttpResponse response) throws ParseException, IOException {
    StringBuilder sb = new StringBuilder(1024);
    HttpEntity entity = response.getEntity();
    sb.append(response.getStatusLine());
    sb.append(" ");
    sb.append(EntityUtils.toString(entity, StandardCharsets.UTF_8));
    EntityUtils.consume(entity);
    return sb.toString();
}

From source file:uk.theretiredprogrammer.nbpcglibrary.remoteclient.RemotePersistenceUnitProvider.java

/**
 * Execute Single Command - send a single command to executed by remote data
 * source./*from w  ww .jav  a  2s .c  o  m*/
 *
 * @param tablename the name of the table to be accessed
 * @param action the action request on that table
 * @param request the command object
 * @return the response object
 * @throws IOException if problems with parsing command data or problems
 * executing the command
 */
public synchronized JsonObject executeSingleCommand(String tablename, String action, JsonObject request)
        throws IOException {
    JsonStructure res = null;
    HttpPost httpPost = new HttpPost(url + tablename + "/" + action);
    httpPost.setEntity(new StringEntity(request.toString(), APPLICATION_JSON));
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity responsebody = response.getEntity();
            try (JsonReader jsonReader = Json.createReader(responsebody.getContent())) {
                res = jsonReader.read();
            }
            EntityUtils.consume(responsebody);
        }
    }
    if (res instanceof JsonObject) {
        return (JsonObject) res;
    } else {
        throw new JsonConversionException();
    }
}

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

@Test
public void testList() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

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

    LOG.info("Connecting to " + uri.toString());

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

        assertEquals(doc.getVenues().size(), 1);
        testEquality(doc.getVenues().get(0), TestFixture.INSTANCE.venue);

        EntityUtils.consume(entity);
    }/*  w w w . j  a  v  a  2 s .c om*/
}

From source file:com.splunk.shuttl.archiver.distributed.DistributedFlushTest.java

private void assertBucketsExistInFlushResponse(HttpResponse response, LocalBucket... buckets)
        throws IllegalStateException, IOException {
    try {/*from  w w w . j  av  a 2  s.c  o  m*/
        String content = IOUtils.toString(response.getEntity().getContent());
        for (LocalBucket b : buckets)
            assertTrue(content.contains(b.getName()), "Content" + content + " did not contain: " + b.getName());
    } finally {
        EntityUtils.consume(response.getEntity());
    }
}

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

/**
 *
 * @param restPath//from  w  w  w .  j a v a 2 s .c o  m
 * @param params
 * @return
 */
public String postRequest(String restPath, List<NameValuePair> params) {
    HttpPost httpPost = new HttpPost(prepareRequestURL(restPath, new ArrayList<NameValuePair>()));
    CloseableHttpResponse response = null;
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String content = new Scanner(entity.getContent()).useDelimiter("\\Z").next();
        EntityUtils.consume(entity);
        return content;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

From source file:org.olat.test.rest.UserRestClient.java

public UserVO createAuthor() throws IOException, URISyntaxException {
    RestConnection restConnection = new RestConnection(deploymentUrl);
    assertTrue(restConnection.login(username, password));

    UserVO user = createUser(restConnection, "Selena", "Auth");

    RolesVO roles = new RolesVO();
    roles.setAuthor(true);//from  w  ww  . j a v  a 2  s . co  m

    //update roles of author
    URI request = getUsersURIBuilder().path(user.getKey().toString()).path("roles").build();
    HttpPost method = restConnection.createPost(request, MediaType.APPLICATION_JSON);
    restConnection.addJsonEntity(method, roles);
    HttpResponse response = restConnection.execute(method);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    restConnection.shutdown();
    return user;
}