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.openqa.selenium.remote.server.SessionLogsTest.java

private static JSONObject getValueForPostRequest(URL serverUrl) throws Exception {
    String postRequest = serverUrl + "/logs";
    HttpClient client = new DefaultHttpClient();
    HttpPost postCmd = new HttpPost(postRequest);
    HttpResponse response = client.execute(postCmd);
    HttpEntity entity = response.getEntity();
    InputStreamReader reader = new InputStreamReader(entity.getContent(), Charsets.UTF_8);
    try {// w  w  w  .  j av  a 2s  .c o m
        String str = CharStreams.toString(reader);
        return new JSONObject(str).getJSONObject("value");
    } finally {
        EntityUtils.consume(entity);
        reader.close();
    }
}

From source file:org.jboss.as.test.integration.web.security.external.WebSecurityExternalAuthTestCase.java

protected void makeCall(String user, int expectedStatusCode) throws Exception {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");
        httpget.addHeader("User", user);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();

        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    }//from  www  .  j  a v a  2 s . c o  m
}

From source file:eu.prestoprime.p4gui.connection.SearchConnection.java

public static String searchByOaiPmh(P4Service service, String params) {
    String string = null;/*  w  w  w.j  a va 2s  . c o m*/
    try {
        params = params.replaceAll("--", "&");
        String path = service.getURL() + "/search/oai?" + params;
        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpRequestBase request = new HttpGet(path);
        HttpResponse response = client.executeRequest(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is1 = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is1));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            string = sb.toString();
            is1.close();
        }
        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return string;
}

From source file:org.blocks4j.reconf.infra.http.layer.SimpleHttpResponse.java

private void consumeBody() {
    if (response.getEntity() == null) {
        body = StringUtils.EMPTY;/*from w  w  w.j av  a2s. co m*/
    }

    HttpEntity entity = response.getEntity();
    String encoding = getContentEncoding(entity);
    String charset = getContentCharSet(entity);

    try {
        if ("gzip".equalsIgnoreCase(encoding)) {
            GzipDecompressingEntity gzip = new GzipDecompressingEntity(entity);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            gzip.writeTo(output);
            body = output.toString(charset);

        } else {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
            StringBuilder result = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                result.append(line);
                if (reader.ready()) {
                    result.append(LineSeparator.value());
                }
            }
            body = result.toString();
        }
    } catch (Exception e) {
        exception = e;

    } finally {
        try {
            EntityUtils.consume(entity);
        } catch (Exception e) {
            exception = e;
        }
    }
}

From source file:com.msds.km.service.Impl.DrivingLicenseRecognitionServcieiImpl.java

private String recognitionInternal(byte[] b) throws Exception {
    try {//from  ww  w  .j av  a  2s.  c  om
        HttpPost httppost = new HttpPost(POST_URL);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addBinaryBody("img", b, ContentType.MULTIPART_FORM_DATA, "test.jpg")
                .addTextBody("action", "driving").addTextBody("callbackurl", "/idcard/").build();

        httppost.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            String content = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());
            return content;
        } catch (IOException e) {
            throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.",
                    e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                throw new Exception(
                        "can not post request to the url:" + POST_URL + ", please check the network.", e);
            }
        }
    } catch (ClientProtocolException e) {
        throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.", e);
    } catch (IOException e) {
        throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.", e);
    }
}

From source file:dk.deck.aws.price.api.AbstractPriceList.java

protected String getRequestAsString(String url) throws IOException {
    String content = null;/* w  ww  .  java  2 s  . c o  m*/
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpGet);
    try {
        // System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new IllegalStateException(response.getStatusLine().getStatusCode() + " "
                    + response.getStatusLine().getReasonPhrase());
        } else {
            content = IOUtils.toString(entity.getContent());
        }
        EntityUtils.consume(entity);
    } finally {
        httpGet.releaseConnection();
    }
    return content;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.SimplifiedQueryJsonTests.java

protected void validateNonEmptyResponse(String query) throws XPathExpressionException, IOException,
        ParserConfigurationException, SAXException, JSONException {
    String queryUrl = OSLCUtils.addQueryStringToURL(currentUrl, query);

    // Send JSON request
    HttpResponse response = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, creds, OSLCConstants.CT_JSON,
            headers);//from  www.ja v  a2  s  .  co m

    int statusCode = response.getStatusLine().getStatusCode();
    if (HttpStatus.SC_OK != statusCode) {
        EntityUtils.consume(response.getEntity());
        throw new IOException("Response code: " + statusCode + " for " + queryUrl);
    }

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

    //
    // Validate JSON response
    //
    // TODO: add more detailed validation
    assertTrue("query response is in Json format.", JSON.parse(responseBody) instanceof JSONArtifact);
}

From source file:org.springframework.social.reddit.connect.RedditOAuth2Template.java

private String getAccessToken(String code, String redirectUrl)
        throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*w  ww  .j a  v  a 2s  . c  o  m*/

        //Reddit Requires clientId and clientSecret be attached via basic auth
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("ssl.reddit.com", 443),
                new UsernamePasswordCredentials(clientId, clientSecret));

        HttpPost httppost = new HttpPost(RedditPaths.OAUTH_TOKEN_URL);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>(3);
        nvps.add(new BasicNameValuePair("code", code));
        nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nvps.add(new BasicNameValuePair("redirect_uri", redirectUrl));

        httppost.setEntity(new UrlEncodedFormEntity(nvps));
        httppost.addHeader("User-Agent", "a unique user agent");
        httppost.setHeader("Accept", "any;");

        HttpResponse request = httpclient.execute(httppost);
        HttpEntity response = request.getEntity(); // Reddit response containing accessToken

        if (response != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getContent()));
            StringBuilder content = new StringBuilder();
            String line;
            while (null != (line = br.readLine())) {
                content.append(line);
            }
            System.out.println(content.toString());
            Map json = (Map) JSONValue.parse(content.toString());
            if (json.containsKey("access_token")) {
                return (String) (json.get("access_token"));
            }
        }
        EntityUtils.consume(response);
    } finally {
        httpclient.getConnectionManager().shutdown(); //cleanup
    }
    return null;
}

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

@Test
public void testListAll() 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.getBandContests().size(), 1);
        testEquality(doc.getBandContests().get(0), TestFixture.INSTANCE.bandContest);

        EntityUtils.consume(entity);
    }//from w w  w  .jav a2s. c  om
}

From source file:com.beginner.core.utils.HttpUtil.java

/**
 * <p>To request the GET way.</p>
 * //www.ja  v a 2s  . co m
 * @param url      request URI
 * @param timeout   request timeout time in milliseconds(The default timeout time for 30 seconds.)
 * @return String   response result
 * @throws Exception
 * @since 1.0.0
 */
public static String get(String url, Integer timeout) throws Exception {

    // Validates input
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("The url cannot be null and cannot be empty.");

    //The default timeout time for 30 seconds
    if (null == timeout)
        timeout = 30000;

    CloseableHttpClient httpClient = HttpClients.createDefault();

    CloseableHttpResponse httpResponse = null;
    String result = null;

    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        httpResponse = httpClient.execute(httpGet);

        HttpEntity entity = httpResponse.getEntity();
        result = EntityUtils.toString(entity);

        EntityUtils.consume(entity);
    } catch (Exception e) {
        logger.error("GET?", e);
        return null;
    } finally {
        if (null != httpResponse)
            httpResponse.close();
        if (null != httpClient)
            httpClient.close();
    }
    return result;
}