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:oracle.custom.ui.oauth.vo.OpenIdConfiguration.java

public static OpenIdConfiguration getButDontSave(String baseUrl) throws Exception {

    String url = baseUrl + endpoint;
    System.out.println("URL is '" + url + "'");
    HttpClient client = ServerUtils.getClient();
    URI uri = new URI(url);
    HttpGet get = new HttpGet(uri);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    HttpResponse response = client.execute(host, get);
    try {//from w  w  w .jav a2 s  . co  m
        HttpEntity entity2 = response.getEntity();
        String res = EntityUtils.toString(entity2);
        EntityUtils.consume(entity2);
        ObjectMapper mapper = new ObjectMapper();
        //res = res.replaceAll("secureoracle.idcs.internal.oracle.com:443", "oc-140-86-12-131.compute.oraclecloud.com");
        OpenIdConfiguration openIdConfigInstance = mapper.readValue(res, OpenIdConfiguration.class);

        return openIdConfigInstance;
    } finally {
        if (response instanceof CloseableHttpResponse) {
            ((CloseableHttpResponse) response).close();
        }
    }
}

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

public static boolean checkIdentifier(P4Service service, String identifier) {
    try {/*from   w w  w.  j  a va2 s .c  o  m*/
        String path = service.getURL() + "/access/dip/checkdcid/" + identifier;
        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpRequestBase request = new HttpGet(path);
        HttpEntity entity = client.executeRequest(request).getEntity();
        if (entity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            if ((line = reader.readLine()) != null) {
                if (line.equals("available")) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:uk.codingbadgers.bootstrap.download.EtagDownload.java

public void download() {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet assetRequest = new HttpGet(remote);
    assetRequest.setHeader(new BasicHeader("Accept", BootstrapConstants.ASSET_MIME_TYPE));

    if (local.exists()) {
        assetRequest//from  w  w w  . ja  v  a 2  s.co  m
                .setHeader(new BasicHeader("If-None-Match", "\"" + ChecksumGenerator.createMD5(local) + "\""));
    }

    try {
        HttpResponse response = client.execute(assetRequest);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
            // No need to download, its already latest
            System.out.println("File " + local.getName() + " is up to date with remote, no need to download");
        } else if (status.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
                || status.getStatusCode() == HttpStatus.SC_OK) {
            // Update local version
            System.err.println("Downloading " + local.getName());

            HttpEntity entity = response.getEntity();

            ReadableByteChannel rbc = Channels.newChannel(entity.getContent());
            FileOutputStream fos = new FileOutputStream(local);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

            EntityUtils.consume(entity);

            String hash = "\"" + ChecksumGenerator.createMD5(local) + "\"";
            if (!hash.equalsIgnoreCase(response.getFirstHeader("Etag").getValue())) {
                throw new BootstrapException(
                        "Error downloading file (" + local.getName() + ")\n[expected hash: "
                                + response.getFirstHeader("Etag").getValue() + " but got " + hash + "]");
            }

            System.out.println("Downloaded " + local.getName());

        } else {
            throw new BootstrapException("Error getting update from github. Error: " + status.getStatusCode()
                    + status.getReasonPhrase());
        }
    } catch (IOException ex) {
        throw new BootstrapException(ex);
    } finally {
        close(client);
    }
}

From source file:org.eclipse.koneki.protocols.omadm.client.http.internal.DMHttpClient.java

@Override
protected void sendAndReceiveMessage(final URI server, final String encoding, final DMMessenger messenger)
        throws IOException, DMClientException {
    try {/* w ww. j ava2  s .co m*/
        final HttpPost post = new HttpPost(server);

        final EntityTemplate entity = new EntityTemplate(new ContentProducer() {

            @Override
            public void writeTo(final OutputStream out) throws IOException {
                try {
                    messenger.writeMessage(out);
                } catch (final DMClientException e) {
                    throw new IOException(e);
                }
            }

        });
        entity.setChunked(false);
        entity.setContentEncoding(encoding);
        entity.setContentType("application/vnd.syncml.dm+xml"); //$NON-NLS-1$
        post.setEntity(entity);

        final HttpResponse response = this.httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
            throw new DMClientException(response.getStatusLine().toString());
        }

        messenger.readMessage(response.getEntity().getContent());

        EntityUtils.consume(response.getEntity());
    } catch (final IOException e) {
        if (e.getCause() != null && e.getCause() instanceof DMClientException) {
            throw (DMClientException) e.getCause();
        } else {
            throw e;
        }
    }
}

From source file:com.easycode.common.HttpUtil.java

public static byte[] httpPost(String url, List<FormItem> blist) throws Exception {
    byte[] ret = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName("UTF-8"));
    if (blist != null) {
        for (FormItem f : blist) {
            reqEntity.addPart(f.getName(), f.getCtx());
        }// w  w w.j a va 2 s .c  om
    }
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);

    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        InputStream tis = resEntity.getContent();

        java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = tis.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        ret = out.toByteArray();
    }
    EntityUtils.consume(resEntity);
    try {
        httpclient.getConnectionManager().shutdown();
    } catch (Exception ignore) {
    }
    return ret;
}

From source file:org.geosdi.geoplatform.connector.server.request.PostConnectorRequest.java

@Override
public String getResponseAsString() throws Exception {
    String content;/*from  w w w . ja  v  a2s  .c  o m*/

    HttpPost httpPost = this.getPostMethod();
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpPost);
    HttpEntity responseEntity = httpResponse.getEntity();

    if (responseEntity != null) {
        InputStream is = responseEntity.getContent();
        content = CharStreams.toString(new InputStreamReader(is, UTF_8));
        EntityUtils.consume(responseEntity);
    } else {
        throw new IllegalStateException("Connector Server Error: Connection problem");
    }
    return content;
}

From source file:org.scigap.iucig.controller.ScienceDisciplineController.java

@ResponseBody
@RequestMapping(value = "/getScienceDiscipline", method = RequestMethod.GET)
public String getScienceDiscipline(@RequestParam(value = "selectedCluster") String cluster) {
    String responseJSON = null;// www . j a v  a 2  s.co  m
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpRequestBase disciplines = new HttpGet(
            SCIENCE_DISCIPLINE_URL + "discipline/?format=json&cluster=" + cluster);
    logger.debug("Executing REST GET request" + disciplines.getRequestLine());

    try {
        httpClient = (DefaultHttpClient) WebClientDevWrapper.wrapClient(httpClient);
        HttpResponse response = httpClient.execute(disciplines);
        HttpEntity entity = response.getEntity();
        if (entity != null && response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
            responseJSON = convertStreamToString(entity.getContent());
        }
        EntityUtils.consume(entity);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return responseJSON;
}

From source file:ch.admin.hermes.etl.load.HermesOnlineCrawler.java

/**
 * Liefert alle Szenarion URL's // w  w w.j ava  2s.  co m
 * @return 
 * @throws Exception Allgemeiner I/O Fehler
 */
public String[] getScenarios() throws Exception {
    ArrayList<String> s = new ArrayList<String>();
    HttpGet get = new HttpGet(url + scenarios);

    try {
        HttpResponse response = httpClient.execute(get);

        HttpEntity entity = response.getEntity();
        String pageHTML = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        Document document = Jsoup.parse(pageHTML);
        Elements elements = document.getElementsByAttribute("href");
        for (Element e : elements) {
            if (e.attr("href").startsWith("/szenarien")) {
                String attr = e.attr("href").substring(scenario_prefix.length());
                attr = attr.substring(0, attr.lastIndexOf('/'));
                s.add(attr);
            }
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null,
                "Keine Online Verbindung mglich. Bitte Szenario manuell downloaden, entpacken und bei XMl Model eintragen.",
                "Keine Verbindung zu http://www.hermes.admin.ch", JOptionPane.WARNING_MESSAGE);

    }
    return (s.toArray(new String[s.size()]));
}

From source file:com.couchbase.capi.TestCouchbase.java

protected void validateMissingPoolResponse(HttpResponse response) throws IOException {
    Assert.assertEquals(404, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());
}

From source file:com.foundationdb.http.CrossOriginITBase.java

@After
public final void tearDown() throws IOException {
    if (response != null) {
        EntityUtils.consume(response.getEntity());
    }/*from w  ww.  j  a  v  a2  s .  c  om*/
    if (client != null) {
        client.getConnectionManager().shutdown();
    }
}