如何在Apache HttpClient版本4.3.3中设置套接字缓冲区大小?
答案 0 :(得分: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();
}
答案 1 :(得分:1)
使用所需的缓冲区大小创建自定义ConnectionConfig对象,并在创建HttpClient对象时将其作为参数传递。例如:
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());
}
还有许多其他可配置选项,checkout the API表示完整列表。