简体   繁体   English

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

[英]Apache HTTP components: Set timeout on default client

I'm creating a default HTTP client using HttpClients.createDefault() , but I'd like to change the default timeout (it seems pretty long, it's been over a minute now and it didn't time out). 我正在使用HttpClients.createDefault()创建一个默认的HTTP客户端,但是我想更改默认的超时时间(看起来很长,现在已经超过一分钟了,并且没有超时)。

Is it possible to change only the timeout of the default client or do I have to build the client from scratch? 是否可以仅更改默认客户端的超时,还是必须从头开始构建客户端?

I'm using version 4.3.3 of the apache HTTP client. 我正在使用apache HTTP客户端的4.3.3版本。

Why using the default client when timeouts are easily configurable for custom clients? 如果可以轻松为自定义客户端配置超时,为什么要使用默认客户端? The following code does the job for httpclient 4.3.4 . 以下代码完成了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();
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);

Or you can set the timeout in HttpConnectionParams . 或者,您可以在HttpConnectionParams中设置超时。

EDIT 编辑

With HttpClient = 4.3, from the official documentation : 使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM