HttpPost如何设置超时时间
时间: 2023-09-27 13:04:52 浏览: 163
可以使用 `RequestConfig` 对象来设置 `HttpPost` 的超时时间。以下是示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) {
// 创建 HttpClient 实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpPost 请求
HttpPost httpPost = new HttpPost("http://example.com/api");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
StringEntity requestEntity = new StringEntity(requestBody, "UTF-8");
httpPost.setEntity(requestEntity);
// 设置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 连接超时时间
.setSocketTimeout(5000) // 读取超时时间
.build();
httpPost.setConfig(requestConfig);
try {
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 处理响应
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
}
} finally {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在上面的示例代码中,通过 `RequestConfig` 对象设置了连接超时时间和读取超时时间,分别为 5000 毫秒。你可以根据实际需求调整超时时间的数值。
阅读全文