java http 服务端 设置读超时时间
时间: 2024-09-18 11:10:07 浏览: 30
liaotian.rar_java 客户端 服务端
在Java中设置HTTP服务端的读超时时间通常涉及到使用`HttpURLConnection`或者第三方库如`Apache HttpClient`或`OkHttp`。这里以`HttpURLConnection`为例,你可以通过创建连接时设置`SocketTimeout`属性来实现读操作的超时:
```java
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(5000); // 设置超时时间为5秒,单位为毫秒
try {
connection.connect(); // 连接服务器
// 从服务器读取数据...
} catch (IOException e) {
if (e instanceof SocketTimeoutException) {
System.out.println("读取超时!");
} else {
e.printStackTrace();
}
}
// 关闭连接
connection.disconnect();
```
如果你使用的是`Apache HttpClient`,可以在`CloseableHttpResponse`上设置连接管理器的超时:
```java
HttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("http://example.com");
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
CloseableHttpResponse response = httpClient.execute(request, config);
try {
// 读取响应...
} finally {
response.close();
}
```
对于`OkHttp`, 在`OkHttpClient.Builder`中添加`connectTimeout`和`readTimeout`:
```java
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.readTimeout(5000, TimeUnit.MILLISECONDS)
.build();
Response response = client.newCall(new Request.Builder()
.url("http://example.com")
.build())
.execute();
```
阅读全文