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.intel.cosbench.client.amplistor.AmpliClient.java

public boolean login() throws IOException, HttpException {
    String storageUrl = "http://" + this.host + ":" + this.port;

    HttpHead method = HttpClientUtil.makeHttpHead(storageUrl);
    HttpResponse response = null;/*from w ww.jav a  2 s .  com*/
    try {
        response = client.execute(method);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return true;
        }

    } finally {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    }

    return false;
}

From source file:com.okta.sdk.framework.JsonApiClient.java

@Override
protected <T> T unmarshall(HttpResponse response, TypeReference<T> clazz) throws IOException {
    if (response.getEntity() == null || clazz.getType().equals(Void.class)) {
        EntityUtils.consume(response.getEntity());
        return null;
    }//from  w w w.j a v  a 2s. c om
    InputStream inputStream = response.getEntity().getContent();
    JsonParser parser = objectMapper.getFactory().createParser(inputStream);
    T toReturn = parser.readValueAs(clazz);
    EntityUtils.consume(response.getEntity());
    return toReturn;
}

From source file:org.apache.clerezza.commons.rdf.impl.sparql.SparqlClient.java

public Object queryResult(final String query) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
    HttpEntity entity2 = response2.getEntity();
    try {// w w w .  j ava  2 s .c om
        InputStream in = entity2.getContent();
        final String mediaType = entity2.getContentType().getValue();
        if ("application/sparql-results+xml".equals(mediaType)) {
            return SparqlResultParser.parse(in);
        } else {
            //assuming RDF response
            //FIXME clerezza-core-rdf to clerezza dependency
            Parser parser = Parser.getInstance();
            return parser.parse(in, mediaType);
        }
    } finally {
        EntityUtils.consume(entity2);
        response2.close();
    }

}

From source file:org.apache.hadoop.gateway.dispatch.HdfsDispatch.java

public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException {
    HttpEntity entity = createRequestEntity(request);
    URI requestUri = getDispatchUrl(request);

    auditor.audit(Action.DISPATCH, request.getRequestURI(), ResourceType.URI, ActionOutcome.UNAVAILABLE);
    if ("CREATE".equals(request.getParameter("op"))) {
        HttpPut clientRequest = new HttpPut(requestUri);
        HttpClient client = new DefaultHttpClient();
        HttpResponse clientResponse = client.execute(clientRequest);
        EntityUtils.consume(clientResponse.getEntity());
        if (clientResponse.getStatusLine().getStatusCode() == HttpStatus.TEMPORARY_REDIRECT_307) {
            Header locationHeader = clientResponse.getFirstHeader("Location");
            String location = locationHeader.getValue();
            clientRequest = new HttpPut(location);
            clientRequest.setEntity(entity);
            executeRequest(clientRequest, request, response);
        }//from   w w w . j a  va 2s.  c o m
    } else {
        HttpPut clientRequest = new HttpPut(requestUri);
        if (entity.getContentLength() > 0) {
            clientRequest.setEntity(entity);
        }
        executeRequest(clientRequest, request, response);
    }
}

From source file:httpServerClient.app.QuickStart.java

public static void sendMessage(String[] args) throws Exception {
    // arguments to run Quick start POST:
    // args[0] POST
    // args[1] IPAddress of server
    // args[2] port No.
    // args[3] user name
    // args[4] myMessage
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {/* w w w  .ja  va  2  s .  c  o m*/
        HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage");
        // httpPost.setEntity(new StringEntity("lubo je kral"));
        httpPost.setEntity(
                new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}"));
        CloseableHttpResponse response1 = httpclient.execute(httpPost);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();

            /*
             * Vypisanie odpovede do konzoly a discard dat zo serveru.
             */

            System.out.println(EntityUtils.toString(entity1));
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:com.mycompany.bankinterface.eth.EthereumEidProvider.java

private String sendGetMessage(String location) throws IOException {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(location);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        HttpEntity entity = response.getEntity();
        String content = IOUtils.toString(entity.getContent());
        EntityUtils.consume(entity);
        return content;
    }/*from w  w w . j a v  a 2  s.c o m*/

}

From source file:co.cask.cdap.gateway.collector.NettyFlumeCollectorTest.java

@Test
public void testFlumeEnqueue() throws Exception {
    CConfiguration cConfig = GatewayTestBase.getInjector().getInstance(CConfiguration.class);
    cConfig.setInt(Constants.Gateway.STREAM_FLUME_PORT, 0);
    NettyFlumeCollector flumeCollector = GatewayTestBase.getInjector().getInstance(NettyFlumeCollector.class);
    flumeCollector.startAndWait();/*from www  . j a va 2 s  .co  m*/
    int port = flumeCollector.getPort();

    String streamName = "flume-stream";
    // Create new stream.
    HttpResponse response = GatewayFastTestsSuite.doPut("/v2/streams/" + streamName);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    // Send flume events
    int totalEvents = 12;
    // Send 6 events one by one
    for (int i = 0; i < totalEvents / 2; i++) {
        sendFlumeEvent(port, createFlumeEvent(i, streamName));
    }

    // Send 6 events in a batch
    sendFlumeEvents(port, streamName, totalEvents / 2, totalEvents);

    flumeCollector.stopAndWait();

    // Get all stream events
    response = GatewayFastTestsSuite.doGet("/v2/streams/" + streamName + "/events?limit=13");
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());

    long lastEventTime = 0L;
    Reader reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8);
    try {
        List<StreamEvent> events = GSON.fromJson(reader, new TypeToken<List<StreamEvent>>() {
        }.getType());
        Assert.assertEquals(totalEvents, events.size());
        for (int i = 0; i < totalEvents; i++) {
            StreamEvent event = events.get(i);
            Assert.assertEquals(Integer.toString(i), event.getHeaders().get("messageNumber"));
            Assert.assertEquals("This is a message " + i, Charsets.UTF_8.decode(event.getBody()).toString());

            lastEventTime = event.getTimestamp();
        }
    } finally {
        reader.close();
    }

    // Fetch again, there should be no more events
    response = GatewayFastTestsSuite
            .doGet("/v2/streams/" + streamName + "/events?start=" + (lastEventTime + 1L));
    Assert.assertEquals(HttpResponseStatus.NO_CONTENT.getCode(), response.getStatusLine().getStatusCode());
}

From source file:net.uytrewq.jogp.impl.ClientImpl.java

public OgpValues parseURL(String url) throws IOException, HtmlException {
    HttpEntity entity = null;//from  w w w.  ja va  2  s  .co m
    try {
        entity = getEntity(url);
        return parse(url, new InputSource(entity.getContent()));
    } catch (ClientProtocolException e) {
        throw new IOException(e);
    } finally {
        try {
            EntityUtils.consume(entity);
        } catch (IOException e) {
            // ignore
            logger.error("failed to consume entity", e);
        }
    }
}

From source file:de.bytefish.fcmjava.client.utils.HttpUtils.java

private static <TRequestMessage, TResponseMessage> TResponseMessage internalPost(
        HttpClientBuilder httpClientBuilder, IFcmClientSettings settings, TRequestMessage requestMessage,
        Class<TResponseMessage> responseType) throws Exception {

    try (CloseableHttpClient client = httpClientBuilder.build()) {

        // Initialize a new post Request:
        HttpPost httpPost = new HttpPost(settings.getFcmUrl());

        // Get the JSON representation of the given request message:
        String requestJson = JsonUtils.getAsJsonString(requestMessage);

        // Set the JSON String as data:
        httpPost.setEntity(new StringEntity(requestJson));

        // Execute the Request:
        try (CloseableHttpResponse response = client.execute(httpPost)) {

            // Get the HttpEntity of the Response:
            HttpEntity entity = response.getEntity();

            // If we don't have a HttpEntity, we won't be able to convert it:
            if (entity == null) {
                // Simply return null (no response) in this case:
                return null;
            }/*from   w ww. ja v a2  s .c  om*/

            // Get the JSON Body:
            String responseBody = EntityUtils.toString(entity);

            // Make Sure it is fully consumed:
            EntityUtils.consume(entity);

            // And finally return the Response Message:
            return JsonUtils.getEntityFromString(responseBody, responseType);
        }
    }
}

From source file:org.hardisonbrewing.s3j.FileResponseHandler.java

@Override
public File handleResponse(HttpResponse httpResponse) throws HttpResponseException, IOException {

    System.out.println("  Response Headers");
    HttpUtil.printHeaders(httpResponse);

    HttpUtil.validateResponseCode(httpResponse);

    File file = FileUtils.createTempFile();

    long contentLength = 0;

    HttpEntity entity = null;/* w ww.jav a 2 s .c  o  m*/
    InputStream inputStream = null;
    CountingInputStream countingInputStream = null;
    OutputStream outputStream = null;

    try {

        entity = httpResponse.getEntity();

        contentLength = entity.getContentLength();
        validateContentLength(contentLength);

        inputStream = entity.getContent();

        inputStream = new ProgressInputStream(inputStream, contentLength);

        // put this before the cipher so we get the encrypted length
        countingInputStream = new CountingInputStream(inputStream);
        inputStream = countingInputStream;

        if (cipher != null) {
            inputStream = new CipherInputStream(inputStream, cipher);
        }

        outputStream = new FileOutputStream(file);

        IOUtil.copy(inputStream, outputStream);
    } finally {
        IOUtil.close(inputStream);
        EntityUtils.consume(entity);
        IOUtil.close(outputStream);
    }

    long readLength = countingInputStream.getByteCount();
    validateDownloadLength(contentLength, readLength);

    return file;
}