我正在使用HttpClients.createDefault()
创建一个默认的HTTP客户端,但是我想更改默认超时(看起来很长,现在已经过了一分钟而且没有超时)。< / p>
是否可以仅更改默认客户端的超时或者是否必须从头开始构建客户端?
我正在使用apache HTTP客户端的4.3.3版本。
答案 0 :(得分: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();
答案 1 :(得分: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);
或者您可以在HttpConnectionParams中设置超时。
修改强>
HttpClient = 4.3,来自official documentation:
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);