HttpClient之EntityUtils工具類


 今天看到tttpclient-tutorial上面有這樣一句話-----非常的不推薦使用EntityUtils,除非知道Entity是來自可信任的Http Server 而且還需要知道它的最大長度。文檔上面給了如下示例:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        long len = entity.getContentLength();
        if (len != -1 && len < 2048) {
            System.out.println(EntityUtils.toString(entity));
        } else {
            // Stream content out
        }
    }
} finally {
    response.close();
}

看這意思,contentLength < 2048,你就直接干吧, 否則你還是自已拿着stream玩吧!

無論看了下EntityUtils.toString(entity)方法的源碼,現記錄一下,以便於復習

 

private static String toString(
            final HttpEntity entity,
            final ContentType contentType) throws IOException {
        final InputStream inStream = entity.getContent();
        if (inStream == null) {
            return null;
        }
        try {
            Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
                    "HTTP entity too large to be buffered in memory");
            int capacity = (int)entity.getContentLength();
            if (capacity < 0) {
                capacity = DEFAULT_BUFFER_SIZE;
            }
            Charset charset = null;
            if (contentType != null) {
                charset = contentType.getCharset();
                if (charset == null) {
                    final ContentType defaultContentType = ContentType.getByMimeType(contentType.getMimeType());
                    charset = defaultContentType != null ? defaultContentType.getCharset() : null;
                }
            }
            if (charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
            }
            final Reader reader = new InputStreamReader(inStream, charset); final CharArrayBuffer buffer = new CharArrayBuffer(capacity); final char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString();
        } finally {
            inStream.close();
        }
    }

需要注意以下兩點:

  (1)Args.check(entity.getContentLength() <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory"); 其實就是對Entity的大小做了一次檢測,

如果太大推薦就放到內存中,只是這里的閾值是Integer.MAX_VALUE。 

  (2)將InputStream還原成String是時,使用了CharArrayBuffer 類,以前都沒用過了呢, 以后也可以嘗試着用用!

  (3)關流!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM