0

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

user3375401
  • 481
  • 1
  • 9
  • 19

2 Answers2

2
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();
    }
gaurav
  • 39
  • 4
  • That's for pre 4.3, I believe `client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 128 * 1024);` was deprecated – ericpeters Apr 21 '15 at 20:09
1

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.

Todd K
  • 11
  • 1