gpt4 book ai didi

Java HTTP 客户端请求设置超时

转载 作者:行者123 更新时间:2023-11-30 07:09:42 25 4
gpt4 key购买 nike

我想设置请求的超时时间。这是代码,到目前为止我已经得到了。

final HttpClient httpclient = HttpClients.createDefault();
final HttpPost httppost = new HttpPost(address);
httppost.setHeader("Accept", "text/xml");
httppost.setHeader("Content-type", "application/xml; charset=UTF-8");
httppost.setEntity(new StringEntity(body));
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();

我已经试过了(不起作用,一直加载并忽略超时)

// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
client = new DefaultHttpClient(httpParams);

和(这个抛出 java.lang.UnsupportedOperationException)

httpclient = HttpClients.createDefault();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);

还有其他方法可以设置超时吗?我真的不需要响应,所以异步请求之类的东西也可以完成这项工作。

最佳答案

Apache 的 HttpClient 有两个独立的超时:一个是等待建立 TCP 连接的超时时间,另一个是等待后续字节数据的超时时间。

HttpConnectionParams.setConnectionTimeout()用于建立 TCP 连接,而 HttpConnectionParams.setSoTimeout()在等待后续数据字节时使用。

// Creating default HttpClient
HttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParams = httpClient.getParams();

// Setting timeouts
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 30000);

// Rest of your code
final HttpPost httppost = new HttpPost(address);
httppost.setHeader("Accept", "text/xml");
httppost.setHeader("Content-type", "application/xml; charset=UTF-8");
httppost.setEntity(new StringEntity(body));
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();

关于Java HTTP 客户端请求设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22785139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com