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.wuspba.ctams.ws.ITBandContestEntryController.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.getBandContestEntry().size(), 1);
        testEquality(doc.getBandContestEntry().get(0), TestFixture.INSTANCE.bandContestEntry);

        EntityUtils.consume(entity);
    }//w w w .ja  v  a 2  s . co  m
}

From source file:org.wuspba.ctams.ws.ITSoloContestEntryController.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.getSoloContestEntry().size(), 1);
        testEquality(doc.getSoloContestEntry().get(0), TestFixture.INSTANCE.soloContestEntry);

        EntityUtils.consume(entity);
    }/*from w ww .j a  v a 2s .  c o  m*/
}

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

public static Collection<Object[]> getReferencedCatalogUrlsUsingXML(String base)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    staticSetup();//from   www.  j a va  2s.c  om
    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, basicCreds, OSLCConstants.CT_XML, headers);

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

    String respBody = EntityUtils.toString(resp.getEntity());
    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(respBody);

    // ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();
    Node rootElement = (Node) OSLCUtils.getXPath().evaluate("/rdf:RDF/*", baseDoc, XPathConstants.NODE);
    if (rootElement.getNamespaceURI().equals(OSLCConstants.OSLC_V2)
            && rootElement.getLocalName().equals("ServiceProviderCatalog")) {
        data.add(new Object[] { base });
    }

    // Get all ServiceProviderCatalog urls from the base document in order
    // to test them as well,
    // recursively checking them for other ServiceProviderCatalogs further
    // down.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_v2:serviceProviderCatalog/oslc_v2:ServiceProviderCatalog/@rdf:about", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        if (!spcs.item(i).getNodeValue().equals(base)) {
            Collection<Object[]> subCollection = getReferencedCatalogUrlsUsingXML(spcs.item(i).getNodeValue());
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:org.envirocar.server.event.HTTPPushListener.java

private synchronized void pushNewTrack(Track track) {
    HttpResponse resp = null;/*from w ww .  j  ava 2  s. c  o m*/
    try {
        ObjectNode jsonTrack = encoder.encodeJSON(track, DEFAULT_ACCESS_RIGHTS, MediaTypes.TRACK_TYPE);
        String content = writer.writeValueAsString(jsonTrack);
        logger.debug("Entity: {}", content);
        HttpEntity entity = new StringEntity(content, ContentType.create(MediaTypes.TRACK));
        HttpPost hp = new HttpPost(host);
        hp.setEntity(entity);
        resp = this.client.execute(hp);
    } catch (ClientProtocolException e) {
        logger.warn(e.getMessage(), e);
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
    } finally {
        if (resp != null) {
            try {
                EntityUtils.consume(resp.getEntity());
            } catch (IOException e) {
                logger.warn(e.getMessage());
            }
        }
    }
}

From source file:sft.LoginAndBookSFT.java

public void startBooking() throws URISyntaxException, MalformedURLException, ProtocolException, IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    try {//w w w  . j a v  a2s  . c om
        // get cookie
        final HttpGet httpget = new HttpGet("https://sft.ticketack.com");
        final CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            final HttpEntity entity = response1.getEntity();

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

            System.out.println("Initial set of cookies:");
            final 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();
        }

        // login
        final HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("https://sft.ticketack.com/ticket/view/"))
                .addParameter("ticket_number", username).addParameter("ticket_key", password).build();
        final CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            final HttpEntity entity = response2.getEntity();

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

            System.out.println("Post logon cookies:");
            final 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();
        }
    } finally {
        httpclient.close();
    }

    final Cookie _cookie = cookieStore.getCookies().get(0);
    final String mightyCooke = "PHPSESSID=" + _cookie.getValue();

    for (final String _booking : bookings) {

        // get free seatings
        // json https://sft.ticketack.com/screening/infos_json/02c101f9-c62a-445e-ad72-19fb32db34c0
        final String _json = doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/infos_json/");

        final Gson gson = new Gson();
        final Example _allInfos = gson.fromJson(_json, Example.class);

        if (_allInfos.getCinemaHall().getMap() != null) {

            final String _mySeat = getMeAFreeSeat(_json);

            // book on seating
            // 02c101f9-c62a-445e-ad72-19fb32db34c0?format=json&overbook=false&seat=Parkett%20Rechts:1:16
            try {
                if (_mySeat != null)
                    doGet(mightyCooke,
                            _booking + "?format=json&overbook=true&seat=" + URLEncoder.encode(_mySeat, "UTF-8"),
                            "https://sft.ticketack.com/screening/book_on_ticket/");
            } catch (final MalformedURLException exception) {
                System.err.println("Error: " + exception.getMessage());
            } catch (final ProtocolException exception) {
                System.err.println("Error: " + exception.getMessage());
            } catch (final UnsupportedEncodingException exception) {
                System.err.println("Error: " + exception.getMessage());
            } catch (final IOException exception) {
                System.err.println("Error: " + exception.getMessage());
            }
            System.out.println("booking (seat) done for: " + _booking);

        } else {

            // book
            // https://sft.ticketack.com/screening/book_on_ticket/76c039cc-d1d5-40a1-9a5d-2b1cd4c47799
            // Cookie:PHPSESSID=s1a6a8casfhidfq68tqn2cb565
            doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/book_on_ticket/");
            System.out.println("booking done for: " + _booking);
        }

    }

    System.out.println("All done!");

}

From source file:edu.usu.sdl.apiclient.AbstractService.java

protected void logon() {
    //get the initial cookies
    HttpGet httpget = new HttpGet(loginModel.getServerUrl());
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
        HttpEntity entity = response.getEntity();

        log.log(Level.FINE, "Login form get: {0}", response.getStatusLine());
        EntityUtils.consume(entity);

        log.log(Level.FINEST, "Initial set of cookies:");
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            log.log(Level.FINEST, "None");
        } else {//w w  w  .  j a v a  2s. c om
            for (Cookie cookie : cookies) {
                log.log(Level.FINEST, "- {0}", cookie.toString());
            }
        }
    } catch (IOException ex) {
        throw new ConnectionException("Unable to Connect.", ex);
    }

    //login
    try {
        HttpUriRequest login = RequestBuilder.post().setUri(new URI(loginModel.getSecurityUrl()))
                .addParameter(loginModel.getUsernameField(), loginModel.getUsername())
                .addParameter(loginModel.getPasswordField(), loginModel.getPassword()).build();
        try (CloseableHttpResponse response = httpclient.execute(login)) {
            HttpEntity entity = response.getEntity();

            log.log(Level.FINE, "Login form get: {0}", response.getStatusLine());
            EntityUtils.consume(entity);

            log.log(Level.FINEST, "Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                log.log(Level.FINEST, "None");
            } else {
                for (Cookie cookie : cookies) {
                    log.log(Level.FINEST, "- {0}", cookie.toString());
                }
            }
        }

        //For some reason production requires getting the first page first
        RequestConfig defaultRequestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build();

        HttpUriRequest data = RequestBuilder.get().setUri(new URI(loginModel.getServerUrl()))
                .addHeader(CONTENT_TYPE, MEDIA_TYPE_JSON).setConfig(defaultRequestConfig).build();

        try (CloseableHttpResponse response = httpclient.execute(data)) {
            log.log(Level.FINE, "Response Status from connection: {0}  {1}", new Object[] {
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() });
            HttpEntity entity1 = response.getEntity();
            EntityUtils.consume(entity1);
        }

    } catch (IOException | URISyntaxException ex) {
        throw new ConnectionException("Unable to login.", ex);
    }
}

From source file:cn.digirun.frame.payment.wxpay.util.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    /**// w ww.j  a va  2 s  .c o  m
     * ?PKCS12? ?-- API 
     */
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    /**
     * ?
     */
    //ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+ "");
    //      FileInputStream instream = new FileInputStream(new File("D:/Program Files/MyEclipse 6.5/workspace/weidian/WebRoot/cer/apiclient_cert.p12"));//P12
    FileInputStream instream = new FileInputStream(
            ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + WxpayConfig.cert_path));
    try {
        /**
         * ?
         * MCHID
         * */
        keyStore.load(instream, WxpayConfig.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WxpayConfig.mch_id.toCharArray())//?  
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??

        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.epop.dataprovider.HTMLPage.java

private void getCode(URI uri) throws ClientProtocolException, IOException, ParserConfigurationException {

    // HttpGet httpget = new HttpGet(uri);
    // HttpClient httpclient = new DefaultHttpClient();
    // ResponseHandler<String> responseHandler = new BasicResponseHandler();
    // this.rawCode = httpclient.execute(httpget, responseHandler);
    ///* www .j  ava  2s. c  o m*/
    // TagNode tagNode = new HtmlCleaner().clean(this.rawCode);
    // return new DomSerializer(new CleanerProperties()).createDOM(tagNode);

    HttpGet request = new HttpGet(uri);

    HttpContext HTTP_CONTEXT = new BasicHttpContext();
    HTTP_CONTEXT.setAttribute(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13");
    request.setHeader("Referer", "http://www.google.com");
    request.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11");

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request, HTTP_CONTEXT);

    if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() >= 400) {
        throw new IOException(
                "bad response, error code = " + response.getStatusLine().getStatusCode() + " for " + uri);
    }

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        this.rawCode = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
    }

}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.request.AbstractAuthHttpRequest.java

/**
 * Execute the request and all following requests in the sequence.
 *
 * @param client//w  w  w .  j ava  2  s .c  om
 *          HTTP Client
 * @throws IOException
 *          in case of a problem or the connection was aborted
 * @throws ClientProtocolException
 *          in case of an http protocol error
 */
public final CloseableHttpResponse executeSequence(final CloseableHttpClient client)
        throws IOException, ClientProtocolException {
    // TODO : throw exception if initialization is incorrect
    init();
    CloseableHttpResponse response = null;

    try {
        response = client.execute(httpRequest);
        final HttpEntity entity = response.getEntity();

        // TODO: check the status line

        if (nextRequest != null) {
            nextRequest.configFromPreviousResponse(entity);
            EntityUtils.consume(entity);
        }

    } finally {
        // Close the resource before executing the next request
        if (response != null && nextRequest != null) {
            response.close();
        }
    }

    CloseableHttpResponse lastResponse;
    if (nextRequest != null) {
        lastResponse = nextRequest.executeSequence(client);
    } else {
        lastResponse = response;
    }

    return lastResponse;
}

From source file:org.helm.notation2.wsadapter.MonomerWSSaver.java

/**
 * Adds or updates a single monomer to the monomer store using the URL configured in {@code MonomerStoreConfiguration}
 * ./*from w w w .  j a va  2 s.  c  o  m*/
 * 
 * @param monomer to save
 */
public String saveMonomerToStore(Monomer monomer) {
    String res = "";
    CloseableHttpResponse response = null;

    try {
        response = WSAdapterUtils.putResource(monomer.toJSON(),
                MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesPutFullURL());
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createParser(instream);

        while (!jsonParser.isClosed()) {
            JsonToken jsonToken = jsonParser.nextToken();
            if (JsonToken.FIELD_NAME.equals(jsonToken)) {
                String fieldName = jsonParser.getCurrentName();
                LOG.debug("Field name: " + fieldName);
                jsonParser.nextToken();
                if (fieldName.equals("monomerShortName")) {
                    res = jsonParser.getValueAsString();
                    break;
                }
            }
        }

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        LOG.error("Saving monomer failed!", e);
        return "";
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            LOG.debug("Closing resources failed.", e);
            return res;
        }
    }

    return res;
}