user3375401
user3375401

Reputation: 491

Setting socket buffer size in Apache HttpClient

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

Upvotes: 0

Views: 7939

Answers (2)

Todd K
Todd K

Reputation: 11

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.

Upvotes: 1

gaurav
gaurav

Reputation: 39

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();
    }

Upvotes: 2

Related Questions