Setting socket buffer size in Apache HttpClient

我们两清 提交于 2020-01-07 02:33:07

问题


How do you set the socket buffer size in Apache HttpClient version 4.3.3?


回答1:


HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 128 * 1024);

    HttpPost post = new HttpPost(url);
    String res = null;
    try
    {
        post.addHeader("Connection", "Keep-Alive");
        post.addHeader("Content-Name", selectedFile.getName());
        post.setEntity(new ByteArrayEntity(fileBytes));
        HttpResponse response = client.execute(post);
        res = EntityUtils.toString(response.getEntity());
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }



回答2:


You create a custom ConnectionConfig object with your desired buffer size and pass it as a parameter when creating your HttpClient object. For example:

ConnectionConfig connConfig = ConnectionConfig.custom()
        .setBufferSize(DESIRED_BUFFER_SIZE)
        .build();

try (CloseableHttpClient client = HttpClients.custom()
            .setDefaultConnectionConfig(connConfig)
            .build()) {

    HttpGet get = new HttpGet("http://google.com");
    try (CloseableHttpResponse response = client.execute(get)) {
        // Do something with the response
    } catch (IOException e) {
        System.err.println("Error transferring file: " + e.getLocalizedMessage());
    }
} catch (IOException e) {
    System.err.println("Error connecting to server: " + e.getLocalizedMessage());
}

There are lots of other configurable options available, checkout the API for the full list.



来源:https://stackoverflow.com/questions/22973369/setting-socket-buffer-size-in-apache-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!