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:com.seajas.search.contender.http.SizeRestrictedResponseHandler.java

/**
 * {@inheritDoc}/*from  w w  w  . j  a  v  a  2s.c  om*/
 */
@Override
public SizeRestrictedHttpResponse handleResponse(final HttpResponse response) throws IOException {
    try {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                if (maximumContentLength > 0 && entity.getContentLength() > maximumContentLength) {
                    logger.error("The given stream is too large to process - " + entity.getContentLength()
                            + " > " + maximumContentLength);

                    return null;
                }

                return new SizeRestrictedHttpResponse(response.getLastHeader("Content-Type"),
                        EntityUtils.toByteArray(entity));
            } else
                return null;
        } else {
            logger.error("Could not retrieve the given stream" + (uri != null ? " for URI '" + uri + "'" : "")
                    + ", status = " + response.getStatusLine());

            EntityUtils.consume(response.getEntity());

            return null;
        }
    } catch (IOException e) {
        EntityUtils.consume(response.getEntity());

        throw e;
    }
}

From source file:ru.phsystems.irisx.voice.httpPOST.java

/**
 * This file will post the flac file to google and store the Json String in jsonResponse data member
 *//* w w w  .j  a v  a2s.co m*/
private void postFLAC() {
    try {
        //long start = System.currentTimeMillis();

        // Load the file stream from the given filename
        File file = new File(FLACFileName);

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);

        // Set the content type of the request entity to binary octet stream.. Taken from the chunked post example HTTPClient
        reqEntity.setContentType("binary/octet-stream");
        //reqEntity.setChunked(true); // Uncomment this line, but I feel it slows stuff down... Quick Tests show no difference

        // set the POST request entity...
        httppost.setEntity(reqEntity);

        //System.out.println("executing request " + httppost.getRequestLine());

        // Create an httpResponse object and execute the POST
        HttpResponse response = httpclient.execute(httppost);

        // Capture the Entity and get content
        HttpEntity resEntity = response.getEntity();

        //System.out.println(System.currentTimeMillis()-start);

        String buffer;
        jsonResponse = "";

        br = new BufferedReader(new InputStreamReader(resEntity.getContent()));
        while ((buffer = br.readLine()) != null) {
            jsonResponse += buffer;
        }

        //System.out.println("Content: "+jsonResponse);

        // Close Buffered Reader and content stream.
        EntityUtils.consume(resEntity);
        br.close();
    } catch (Exception ee) {
        // In the event this POST Request FAILED
        //ee.printStackTrace();
        jsonResponse = "_failed_";
    } finally {
        // Finally shut down the client
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.wso2.identity.integration.test.user.mgt.UserMgtUISecurityTestCase.java

/**
 * Tests the open redirect vulnerability in change-passwd-finish.jsp.
 * @throws IOException//from w  w w. ja v  a  2 s  .c  om
 */
@Test(alwaysRun = true, description = "Testing open redirect vulnerability")
public void openRedirectTest() throws IOException {

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost loginPost = new HttpPost(SERVER_URL + LOGIN_PAGE_CONTEXT);

    List<NameValuePair> loginParameters = new ArrayList<>();

    loginParameters.add(new BasicNameValuePair("username", USER_NAME));
    loginParameters.add(new BasicNameValuePair("password", OLD_PASSWORD));

    loginPost.setEntity(new UrlEncodedFormEntity(loginParameters));

    HttpResponse loginResponse = httpClient.execute(loginPost);
    String cookie = loginResponse.getHeaders("Set-Cookie")[0].getValue();

    EntityUtils.consume(loginResponse.getEntity());

    HttpPost post = new HttpPost(SERVER_URL + CHANGE_PASSWORD_CONTEXT);

    post.setHeader("Cookie", cookie);

    List<NameValuePair> urlParameters = new ArrayList<>();

    urlParameters.add(new BasicNameValuePair("pwd_regex", PW_REGEX));
    urlParameters.add(new BasicNameValuePair("username", USER_NAME));
    urlParameters.add(new BasicNameValuePair("isUserChange", "true"));
    urlParameters.add(new BasicNameValuePair("returnPath", RETURN_PATH));
    urlParameters.add(new BasicNameValuePair("currentPassword", NEW_PASSWORD));
    urlParameters.add(new BasicNameValuePair("checkPassword", OLD_PASSWORD));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = httpClient.execute(post);

    String repString = EntityUtils.toString(response.getEntity());

    if (repString != null) {
        Assert.assertFalse(repString.contains(RETURN_PATH), "Possible open redirect vulnerability.");
    } else {
        Assert.assertTrue(false, "Invalid response for password update.");
    }

}

From source file:org.gitana.platform.client.archive.ArchiveImpl.java

@Override
public InputStream download() throws IOException {
    InputStream in = null;/*from  w  ww .  j  av  a2  s  .  com*/

    HttpResponse response = null;
    try {
        response = getRemote().download(getResourceUri() + "/download");

        in = response.getEntity().getContent();
    } catch (Exception ex) {
        try {
            EntityUtils.consume(response.getEntity());
        } catch (Exception ex2) {
        }

        throw new RuntimeException(ex);
    }

    return in;
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

/**
 * Get all pages from the server and construct a map in order to compare content
 * to detect changes or not./* ww  w  .  j  a  v a 2 s  .c  o m*/
 *
 */
private static void getPageMap(String host) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "page");
    inputMap.put("name", "getPageMap");
    inputMap.put("readOnly", true);

    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(host + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(
                ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Got page map from server");
        if (json != null && json.trim().length() > 0) {
            pageMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, String>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.wuspba.ctams.ui.server.ServerUtils.java

public static String post(URI uri, String xml) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    String ret;//from   ww  w  .j  a v a 2  s  .  co m

    httpPost.setEntity(xmlEntity);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        HttpEntity entity = response.getEntity();

        ret = convertEntity(entity);

        EntityUtils.consume(entity);
    }

    return ret;
}

From source file:eu.prestoprime.plugin.ltfsarchiver.client.LTFSClient.java

private LTFSResponse executeRequest(LTFSRequest ltfsRequest) throws LTFSException {
    logger.debug("Calling: " + ltfsRequest);

    try {//from  w  ww.  j a v  a2s .  c  om
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(ltfsRequest.toURL());
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = reader.readLine()) != null)
                    sb.append(line.trim());
                reader.close();
                EntityUtils.consume(entity);

                logger.debug("Received: " + sb);

                LTFSResponse ltfsResponse;
                switch (response.getHeaders("content-Type")[0].getValue()) {
                case "text/plain":
                default:
                    ltfsResponse = new LTFSResponse(sb.toString());
                    break;
                case "application/json":
                    ltfsResponse = new LTFSResponse(new JSONObject(sb.toString()));
                    break;
                }
                return ltfsResponse;
            } else {
                throw new LTFSException("LTFSArchiver returns with empty entity...");
            }
        } else {
            throw new LTFSException(
                    "LTFSArchiver returns with error " + response.getStatusLine().getStatusCode() + "...");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new LTFSException("Unable to contact the LTFSArchiver Web Service...");
    } catch (IOException e) {
        e.printStackTrace();
        throw new LTFSException("Unable to read the response...");
    } catch (JSONException e) {
        e.printStackTrace();
        throw new LTFSException("Unable to parse JSON response...");
    }
}

From source file:client.AsterixDBClient.java

private long executeQuery(Query q) {
    String content = null;/*from  w ww .  j  av  a 2s  .c  o  m*/
    long rspTime = Constants.INVALID_TIME; //initial value
    try {
        roBuilder.setParameter("query", q.getBody());
        URI uri = roBuilder.build();
        httpGet.setURI(uri);

        long s = System.currentTimeMillis(); //Start the timer
        HttpResponse response = httpclient.execute(httpGet); //Actual execution against the server
        HttpEntity entity = response.getEntity();
        content = EntityUtils.toString(entity);
        EntityUtils.consume(entity); //Make sure to consume the results
        long e = System.currentTimeMillis(); //Stop the timer
        rspTime = (e - s); //Total duration

        if (rw != null) { //Dump returned results (if requested)
            rw.println("\n" + q.getName() + "\n" + content);
        }
    } catch (Exception ex) {
        System.err.println("Problem in read-only query execution against Asterix\n" + content);
        ex.printStackTrace();
        return Constants.INVALID_TIME; //invalid time (query was not successful)
    }
    return rspTime;
}

From source file:com.srotya.tau.alerts.media.HttpService.java

/**
 * @param destination/*from  w  w  w  . ja  v a 2 s .  co m*/
 * @param bodyContent
 * @throws AlertDeliveryException
 */
public void sendHttpCallback(String destination, String bodyContent) throws AlertDeliveryException {
    try {
        CloseableHttpClient client = Utils.buildClient(destination, 3000, 3000);
        HttpPost request = new HttpPost(destination);
        StringEntity body = new StringEntity(bodyContent, ContentType.APPLICATION_JSON);
        request.addHeader("content-type", "application/json");
        request.setEntity(body);
        HttpResponse response = client.execute(request);
        EntityUtils.consume(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode < 200 && statusCode >= 300) {
            throw exception;
        }
        client.close();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException
            | AlertDeliveryException e) {
        throw exception;
    }
}

From source file:uk.codingbadgers.bootstrap.tasks.TaskBootstrapUpdateCheck.java

@Override
public void run(Bootstrap bootstrap) {
    try {/*  w w  w  . j  a v a 2s .c o  m*/
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(BootstrapConstants.BOOTSTRAP_UPDATE_URL);
        request.setHeader(new BasicHeader("Accept", BootstrapConstants.GITHUB_MIME_TYPE));

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            JsonArray json = PARSER.parse(new InputStreamReader(entity.getContent())).getAsJsonArray();
            JsonObject release = json.get(0).getAsJsonObject();
            String version = release.get("name").getAsString();

            if (VersionComparator.getInstance().compare(BootstrapConstants.VERSION, version) >= 0) {
                System.out.println("Up to date bootstrap");
            } else {
                Desktop.getDesktop().browse(URI.create(release.get("html_url").getAsString()));
                throw new BootstrapException("Outdated bootstrap.\nPlease update your bootstrap.\n");
            }

            EntityUtils.consume(entity);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            System.err.println("Hit rate limit, skipping update check");
        } else {
            System.err.println(
                    "Error sending request to github. Error " + response.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}