Apache HTTP组件:在默认客户端上设置超时

Aha*_*ius 1 java timeout apache-httpcomponents apache-httpclient-4.x

我正在创建一个默认的HTTP客户端使用HttpClients.createDefault(),但我想更改默认超时(它看起来很长,现在已经超过一分钟而且没有超时).

是否可以仅更改默认客户端的超时或者是否必须从头开始构建客户端?

我正在使用apache HTTP客户端的4.3.3版本.

Red*_*III 7

为什么在自定义客户端可以轻松配置超时时使用默认客户端?以下代码完成了httpclient 4.3.4的工作.

final RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(CONNTECTION_TIMEOUT_MS)
    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MS)
    .setSocketTimeout(SOCKET_TIMEOUT_MS)
    .build();
final CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultRequestConfig(requestConfig)
    .build();
Run Code Online (Sandbox Code Playgroud)

  • Apache 代码中的默认值是什么?有可用的常量/符号吗? (2认同)

rob*_*ann 5

HostConfiguration hostCfg = new HostConfiguration();
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("... your get query string");

int timeout = 5000; //config your value
method.getParams().setSoTimeout(timeout);

//the call
client.executeMethod(hostCfg, method);
Run Code Online (Sandbox Code Playgroud)

或者您可以在HttpConnectionParams中设置超时.

编辑

使用HttpClient = 4.3,来自官方文档:

HttpClientContext clientContext = HttpClientContext.create();
PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
Socket socket = sf.createSocket(clientContext);

int timeout = 1000; // ms <-- 

HttpHost target = new HttpHost("localhost");
InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] {127,0,0,1}), 80);
sf.connectSocket(timeout, socket, target, remoteAddress, null, clientContext);
Run Code Online (Sandbox Code Playgroud)