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.foundationdb.server.service.security.RestSecurityIT.java

private int openRestURL(String request, String query, String userInfo, boolean post) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpRequestBase httpRequest;/*from w w  w . j  a  va 2 s . com*/
    if (post) {
        httpRequest = new HttpPost(getRestURL(request, "", userInfo));
        ((HttpPost) httpRequest).setEntity(new ByteArrayEntity(query.getBytes("UTF-8")));
    } else {
        httpRequest = new HttpGet(getRestURL(request, query, userInfo));
    }
    HttpResponse response = client.execute(httpRequest);
    int code = response.getStatusLine().getStatusCode();
    EntityUtils.consume(response.getEntity());
    client.close();
    return code;
}

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

/**
 * Not required directly from the spec, just mentions that it should be
 * application/rdf+xml//from w  w w . ja v a2s  .  co m
 */
@Test
public void contentTypeIsSuggestedType() throws IOException {
    HttpResponse resp = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl, basicCreds, fContentType,
            headers);
    EntityUtils.consume(resp.getEntity());
    // Make sure the response to this URL was of valid type
    String ct = resp.getEntity().getContentType().getValue();
    assertTrue("Expected content-type \"" + fContentType + "\" received : " + ct, ct.contains(fContentType));
}

From source file:com.tianya.ClientMultipartFormPost.java

public static void preGet(HttpClient httpClient) throws ClientProtocolException, IOException {
    String url = "http://letushow.com/submit";
    HttpGet getReq = new HttpGet(url);

    HttpResponse res = httpClient.execute(getReq);

    getCsrfToken(res);//w w  w .  ja  va 2 s. c o m

    EntityUtils.consume(res.getEntity());
}

From source file:com.telefonica.euro_iaas.sdc.installator.impl.InstallatorPuppetImpl.java

@Override
public void callService(VM vm, String vdc, ProductRelease product, String action) throws InstallatorException {

    HttpPost postInstall = new HttpPost(
            propertiesProvider.getProperty(SystemPropertiesProvider.PUPPET_MASTER_URL) + action + "/" + vdc
                    + "/" + vm.getHostname() + "/" + product.getProduct().getName() + "/"
                    + product.getVersion());

    postInstall.addHeader("Content-Type", "application/json");

    System.out.println("puppetURL: "
            + propertiesProvider.getProperty(SystemPropertiesProvider.PUPPET_MASTER_URL) + action + "/" + vdc
            + "/" + vm.getHostname() + "/" + product.getProduct().getName() + "/" + product.getVersion());

    HttpResponse response;//w  ww .j a  va 2s  .  c o  m

    try {
        response = client.execute(postInstall);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        if (statusCode != 200) {
            String msg = format("[puppet install] response code was: {0}", statusCode);
            log.info(msg);
            throw new InstallatorException(format(msg));
        }

        // generate files in puppet master
        HttpPost postGenerate = new HttpPost(
                propertiesProvider.getProperty(SystemPropertiesProvider.PUPPET_MASTER_URL) + "generate/"
                        + vm.getHostname());

        postGenerate.addHeader("Content-Type", "application/json");

        response = client.execute(postGenerate);
        statusCode = response.getStatusLine().getStatusCode();
        entity = response.getEntity();
        EntityUtils.consume(entity);

        if (statusCode != 200) {
            throw new InstallatorException(
                    format("[install] generete files response code was: {0}", statusCode));
        }
    } catch (IOException e) {
        throw new InstallatorException(e);
    } catch (IllegalStateException e1) {
        throw new InstallatorException(e1);
    }

}

From source file:org.apache.gobblin.http.ApacheHttpResponseHandler.java

protected void consumeEntity(HttpEntity entity) {
    try {/*w  w w  .jav a 2s . c om*/
        EntityUtils.consume(entity);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private void executeRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String target = resolveTargetUrl(req);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(prepareRequest(req, target));
    try {//from   ww  w  .j  a  va  2s.c  om
        String contentType = response.getEntity().getContentType().getValue();

        resp.setContentLength((int) response.getEntity().getContentLength());
        resp.setStatus(response.getStatusLine().getStatusCode());
        resp.setContentType(contentType);

        copyStream(response.getEntity().getContent(), resp.getOutputStream());
    } finally {
        EntityUtils.consume(response.getEntity());
    }
}

From source file:net.liuxuan.Tools.signup.SignupQjvpn.java

public void getLoginForm() throws IOException {

    HttpGet httpget = new HttpGet("http://www.qjvpn.com/user/login.php");
    CloseableHttpResponse response1 = httpclient.execute(httpget);
    try {/*from  w w  w  . ja v a 2s  . c  o  m*/
        HttpEntity entity = response1.getEntity();
        //?once
        String content = EntityUtils.toString(entity);
        //                System.out.println(content);
        System.out.println("--------------");
        System.out.println("--------------");
        Document doc = Jsoup.parse(content);
        //                Elements inputs = doc.select("input[type=text]");
        Elements inputs = doc.select("input[type=hidden]");
        for (int i = 0; i < inputs.size(); i++) {
            Element element = inputs.get(i);
            params.add(new BasicNameValuePair(element.attr("name"), element.attr("value")));
            //                    params.put(element.attr("name"), element.attr("value"));
            System.out.println(element.toString());
            System.out.println(element.attr("name"));
            System.out.println(element.attr("value"));

        }

        System.out.println("--------------");
        System.out.println("--------------");

        System.out.println("--------------");
        System.out.println("--------------");
        System.out.println("Login form get: " + response1.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }
    } finally {
        response1.close();
    }

    //            HttpUriRequest login = RequestBuilder.post()
    //                    .setUri(new URI("http://v2ex.com/signin"))
    //                    .addParameter("u", "mosliu")
    //                    .addParameter("p", "mosesmoses")
    //                    .build();
    //            CloseableHttpResponse response2 = httpclient.execute(login);
    //            try {
    //                HttpEntity entity = response2.getEntity();
    //
    //                System.out.println("Login form get: " + response2.getStatusLine());
    //                
    //                EntityUtils.consume(entity);
    //
    //                System.out.println("Post logon cookies:");
    //                List<Cookie> cookies = cookieStore.getCookies();
    //                if (cookies.isEmpty()) {
    //                    System.out.println("None");
    //                } else {
    //                    for (int i = 0; i < cookies.size(); i++) {
    //                        System.out.println("- " + cookies.get(i).toString());
    //                    }
    //                }
    //                
    //                
    //                
    //            } finally {
    //                response2.close();
    //            }
    //            
    //            
    //            httpget = new HttpGet("http://v2ex.com/signin");
    //            response1 = httpclient.execute(httpget);
    //            try {
    //                HttpEntity entity = response1.getEntity();
    //                String content = EntityUtils.toString(entity);
    //                System.out.println("-----------------content---------------------");
    //                System.out.println(content);
    //                
    //                EntityUtils.consume(entity);
    //            } finally {
    //                response1.close();
    //            }
    //            
    //            
}

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

List<Map<String, RdfTerm>> queryResultSet(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);

    try {/*from   ww  w. ja  va 2  s  .  c o  m*/
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

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

/**
 * Get all forms from the server and construct a map in order to compare content
 * to detect changes or not.//  ww  w  .  ja v a 2  s  . co m
 *
 */
private static void getFormMap(String host) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "form");
    inputMap.put("name", "getFormMap");
    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 form map from server");
        if (json != null && json.trim().length() > 0) {
            formMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, Map<String, Object>>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:io.wcm.caravan.io.http.impl.ApacheHttpClient.java

@Override
public Observable<CaravanHttpResponse> execute(CaravanHttpRequest request) {
    return Observable.create(new Observable.OnSubscribe<CaravanHttpResponse>() {

        @Override/*from w  w w . ja v  a2s .c o  m*/
        public void call(final Subscriber<? super CaravanHttpResponse> subscriber) {
            HttpUriRequest httpRequest = RequestUtil.buildHttpRequest(request);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Execute: {},\n{},\n{}", httpRequest.getURI(), request.toString(),
                        request.getCorrelationId());
            }

            CloseableHttpClient httpClient = (CloseableHttpClient) httpClientFactory.get(httpRequest.getURI());

            long start = System.currentTimeMillis();
            try (CloseableHttpResponse result = httpClient.execute(httpRequest)) {

                StatusLine status = result.getStatusLine();
                HttpEntity entity = new BufferedHttpEntity(result.getEntity());
                EntityUtils.consume(entity);

                boolean throwExceptionForStatus500 = CaravanHttpServiceConfigValidator
                        .throwExceptionForStatus500(request.getServiceId());
                if (status.getStatusCode() >= 500 && throwExceptionForStatus500) {
                    IllegalResponseRuntimeException illegalResponseRuntimeException = new IllegalResponseRuntimeException(
                            request, httpRequest.getURI().toString(), status.getStatusCode(),
                            EntityUtils.toString(entity),
                            "Executing '" + httpRequest.getURI() + "' failed: " + result.getStatusLine());

                    subscriber.onError(illegalResponseRuntimeException);
                    EntityUtils.consumeQuietly(entity);
                } else {

                    CaravanHttpResponse response = new CaravanHttpResponseBuilder()
                            .status(status.getStatusCode()).reason(status.getReasonPhrase())
                            .headers(RequestUtil.toHeadersMap(result.getAllHeaders()))
                            .body(entity.getContent(),
                                    entity.getContentLength() > 0 ? (int) entity.getContentLength() : null)
                            .build();

                    subscriber.onNext(response);
                    subscriber.onCompleted();
                }
            } catch (SocketTimeoutException ex) {
                subscriber.onError(new IOException("Socket timeout executing '" + httpRequest.getURI(), ex));
            } catch (IOException ex) {
                subscriber.onError(new IOException("Executing '" + httpRequest.getURI() + "' failed", ex));
            } catch (Throwable ex) {
                subscriber.onError(
                        new IOException("Reading response of '" + httpRequest.getURI() + "' failed", ex));
            } finally {
                LOG.debug("Took {} ms to load {},\n{}", (System.currentTimeMillis() - start),
                        httpRequest.getURI().toString(), request.getCorrelationId());
            }
        }
    });
}