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.simple.weixin.refund.ClientCustomSSL.java

public static String doRefund(String password, String keyStrore, String url, String data) throws Exception {
    /**/*w w w.ja va2 s  . c  o  m*/
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(keyStrore));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, password.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.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.sonatype.nexus.repositories.metadata.Hc4RawTransport.java

@Override
public void writeRawData(final String path, final byte[] bytes) throws IOException {
    final HttpPut put = new HttpPut(createUrlWithPath(path));
    put.setEntity(new ByteArrayEntity(bytes, ContentType.APPLICATION_XML));
    final HttpResponse response = httpClient.execute(put);
    try {//from   w  w  w .  j av a  2  s .c o  m
        if (response.getStatusLine().getStatusCode() > 299) {
            throw new IOException("The response was not successful: " + response.getStatusLine());
        }
    } finally {
        EntityUtils.consume(response.getEntity());
    }
}

From source file:com.helger.peppol.smpclient.SMPHttpResponseHandlerWriteOperations.java

@Nullable
public Object handleResponse(@Nonnull final HttpResponse aHttpResponse) throws IOException {
    final StatusLine aStatusLine = aHttpResponse.getStatusLine();
    final HttpEntity aEntity = aHttpResponse.getEntity();
    if (aStatusLine.getStatusCode() >= 300)
        throw new HttpResponseException(aStatusLine.getStatusCode(), aStatusLine.getReasonPhrase());
    if (aEntity == null)
        throw new ClientProtocolException("Response from SMP server contains no content");

    EntityUtils.consume(aEntity);
    return null;/*w w  w  .  j  a  v  a 2s .  co  m*/
}

From source file:com.huotu.mallduobao.common.thirdparty.ClientCustomSSL.java

public static String doRefund(String url, String data, String celPath, String celPassword) throws Exception {
    /**/*from w  w w .  jav a 2  s .c o m*/
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(celPath));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, celPassword.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, celPassword.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:com.kurento.test.recorder.RecorderIT.java

private void testRecord(String handler, int statusCode) throws IOException {
    // To follow redirect: .setRedirectStrategy(new LaxRedirectStrategy())
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + getServerPort() + "/kmf-content-api-test/" + handler);
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File("small");
    URL small = new URL(VideoURLs.map.get("small-webm"));
    FileUtils.copyURLToFile(small, file);
    FileBody fb = new FileBody(file);
    multipartEntity.addPart("file", fb);

    HttpEntity httpEntity = multipartEntity.build();
    post.setEntity(httpEntity);/*from  w  w w . jav a 2  s  .c om*/

    EntityUtils.consume(httpEntity);
    HttpResponse response = client.execute(post);
    final int responseStatusCode = response.getStatusLine().getStatusCode();

    log.info("Response Status Code: {}", responseStatusCode);
    log.info("Deleting tmp file: {}", file.delete());

    Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode);
}

From source file:org.etk.common.net.ETKHttpClient.java

public HttpEntity execute(String targetURL) throws ClientProtocolException, IOException {
    HttpHost targetHost = new HttpHost("127.0.0.1", 8080, "http");

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("demo", "gtn"));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet(targetURL);
    Header header = new BasicHeader("Content-Type", "application/json");
    httpget.setHeader(header);/*from   w w w  . j  a v  a  2 s . co  m*/
    HttpResponse response = httpClient.execute(targetHost, httpget, localcontext);
    DumpHttpResponse.dumpHeader(response);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        entity = new BufferedHttpEntity(entity);
    }
    EntityUtils.consume(entity);

    return entity;
}

From source file:org.jets3t.service.impl.rest.httpclient.HttpMethodReleaseInputStream.java

/**
 * Constructs an input stream based on an {@link HttpResponse} object representing an HTTP connection.
 * If a connection input stream is available, this constructor wraps the underlying input stream
 * in an {@link InterruptableInputStream} and makes that stream available. If no underlying connection
 * is available, an empty {@link ByteArrayInputStream} is made available.
 *
 * @param httpMethod//  ww w.  ja v a2s  . c om
 */
public HttpMethodReleaseInputStream(HttpResponse httpMethod) {
    this.httpResponse = httpMethod;
    try {
        this.inputStream = new InterruptableInputStream(httpMethod.getEntity().getContent());
    } catch (IOException e) {
        if (log.isWarnEnabled()) {
            log.warn("Unable to obtain HttpMethod's response data stream", e);
        }
        try {
            EntityUtils.consume(httpMethod.getEntity());
        } catch (Exception ee) {
            // ignore
        }
        this.inputStream = new ByteArrayInputStream(new byte[] {}); // Empty input stream;
    }
}

From source file:org.owasp.benchmark.tools.BenchmarkCrawler.java

public static void sendPost(CloseableHttpClient httpclient, HttpPost post) throws Exception {
    CloseableHttpResponse response = httpclient.execute(post);
    System.out.println("POST " + post.getURI());
    try {/*from ww w  .  j a va  2  s .c  om*/
        HttpEntity entity = response.getEntity();
        System.out.println("--> (" + response.getStatusLine().getStatusCode() + ") ");
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Do get.//  w w w  .j a  v  a2s . c o  m
 *
 * @param uri
 *            the uri
 * @param headers
 *            the headers
 * @return the string
 * @throws Exception
 *             the exception
 */
public static String doGet(URI uri, HashMap<String, String> headers) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String respString = null;
    try {
        /*
         * HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs.
         * 
         * URI uri = new URIBuilder() .setScheme("http") .setHost("hc.apache.org/") // .setPath("/search") // .setParameter("q",
         * "httpclient") // .setParameter("btnG", "Google Search") // .setParameter("aq", "f") // .setParameter("oq", "") .build();
         */

        HttpGet httpGet = new HttpGet(uri);

        for (String key : headers.keySet()) {
            httpGet.addHeader(key, headers.get(key));
        }

        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // 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 entity = response1.getEntity();
            // do something useful with the response body
            if (entity != null) {
                respString = EntityUtils.toString(entity);
            }
            // and ensure it is fully consumed
            EntityUtils.consume(entity);
        } finally {
            response1.close();
        }
    } finally {
        httpclient.close();
    }
    return respString;
}

From source file:com.flicklib.service.HttpClientSourceLoader.java

@Override
public Source loadSource(String url) throws IOException {
    HttpResponse response = null;/*from  www . j ava2s. co  m*/
    try {
        LOGGER.info("Loading " + url);
        HttpGet httpMethod = new HttpGet(url);
        //httpMethod.addRequestHeader("Content-Type","text/html; charset=UTF-8");
        HttpContext ctx = new BasicHttpContext();
        response = client.execute(httpMethod, ctx);

        return buildSource(url, response, httpMethod, ctx);
    } finally {
        if (response != null) {
            EntityUtils.consume(response.getEntity());
        }
    }
}