`setBufferedSize()`方法有什么作用?

时间:2018-05-03 15:38:50

标签: java buffer httpclient

我不知道setBufferSize()方法的作用。任何人都能解释一下它的作用吗?如果我将setBufferSize(4 * 1024)更改为setBufferSize(5)会怎样?当我这样做时,我没有看到任何变化!谁有人解释一下? 感谢。

public class Test {

    public static void main(String[] args) {
        try {
            String url = "DOWNLOAD_LINK";
            HttpGet request = new HttpGet(url);
            ConnectionConfig connectionConfig = ConnectionConfig.custom()
                    .setBufferSize(4 * 1024).build();

            HttpClientBuilder builder = HttpClientBuilder.create();
            builder.setDefaultConnectionConfig(connectionConfig);

            HttpClient client = builder.build();

            HttpResponse response = client.execute(request);

            HttpEntity entity = response.getEntity();

            InputStream inputStream = entity.getContent();
            int len = 0;
            byte[] buffer = new byte[4098];
            while ((len = inputStream.read(buffer)) != -1) {
                System.out.println("len: " + len);
                //write into file , etc.
            }
            inputStream.close();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:2)

以下是SetBufferedSize文档的引用,相当完整:

  

设置响应正文的首选缓冲区大小。该   servlet容器将使用至少与大小一样大的缓冲区   请求。使用的实际缓冲区大小可以找到   getBufferSize。

     

更大的缓冲区允许在任何内容之前写入更多内容   实际发送,从而为servlet提供更多的设置时间   适当的状态代码和标题。较小的缓冲区减少   服务器内存加载并允许客户端开始更多地接收数据   快。

Source

Apache's documentation