java HttpPost 设置超时时间
时间: 2024-05-24 20:06:34 浏览: 161
以下是Java中设置HttpPost超时时间的示例代码:
```java
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class Main {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost("http://example.com/api");
// 设置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 连接超时时间
.setConnectionRequestTimeout(1000) // 从连接池获取连接超时时间
.setSocketTimeout(5000) // 请求获取数据的超时时间
.build();
httpPost.setConfig(requestConfig);
// 执行请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
// 处理响应
// ...
// 关闭连接
response.close();
httpClient.close();
}
}
```
阅读全文