Java中设置HTTP超时时间的方法
在Java中设置HTTP超时时间主要有以下几种方式,具体取决于你使用的HTTP客户端库:

使用HttpURLConnection(JDK内置)
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpTimeoutExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置连接超时时间(毫秒)
connection.setConnectTimeout(5000); // 5秒
// 设置读取超时时间(毫秒)
connection.setReadTimeout(10000); // 10秒
// 其他设置...
connection.setRequestMethod("GET");
// 发送请求并获取响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
connection.disconnect();
}
}
使用Apache HttpClient 4.x
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpClientTimeoutExample {
public static void main(String[] args) throws Exception {
// 创建RequestConfig设置超时
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000) // 连接超时
.setSocketTimeout(10000) // 读取超时
.build();
// 创建HttpClient并应用配置
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.build()) {
HttpGet request = new HttpGet("http://example.com");
try (CloseableHttpResponse response = httpClient.execute(request)) {
System.out.println("Response status: " + response.getStatusLine());
}
}
}
}
使用Apache HttpClient 5.x
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseHttpClientBuilder;
import org.apache.hc.core5.http.HttpResponse;
public class HttpClient5TimeoutExample {
public static void main(String[] args) throws Exception {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000, TimeUnit.MILLISECONDS)
.setConnectionRequestTimeout(5000, TimeUnit.MILLISECONDS)
.setResponseTimeout(10000, TimeUnit.MILLISECONDS)
.build();
try (CloseHttpClient httpClient = CloseHttpClientBuilder.create()
.setDefaultRequestConfig(config)
.build()) {
HttpGet request = new HttpGet("http://example.com");
HttpResponse response = httpClient.execute(request);
System.out.println("Response status: " + response.getCode());
}
}
}
使用OkHttp 3.x/4.x
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class OkHttpTimeoutExample {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS) // 连接超时
.readTimeout(10, TimeUnit.SECONDS) // 读取超时
.writeTimeout(10, TimeUnit.SECONDS) // 写入超时
.build();
Request request = new Request.Builder()
.url("http://example.com")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("Response code: " + response.code());
}
}
}
使用Spring RestTemplate
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public class RestTemplateTimeoutExample {
public static void main(String[] args) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 5秒连接超时
factory.setReadTimeout(10000); // 10秒读取超时
RestTemplate restTemplate = new RestTemplate(factory);
String result = restTemplate.getForObject("http://example.com", String.class);
System.out.println(result);
}
}
使用Spring WebClient(响应式)
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.time.Duration;
public class WebClientTimeoutExample {
public static void main(String[] args) {
WebClient webClient = WebClient.builder()
.clientConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector
.create(org.springframework.http.client.reactor.ReactorClientHttpConnector
.builder()
.responseTimeout(Duration.ofSeconds(10))
.build()))
.build();
Mono<String> result = webClient.get()
.uri("http://example.com")
.retrieve()
.bodyToMono(String.class);
System.out.println(result.block());
}
}
注意事项
- 超时时间单位通常是毫秒
- 不同库的超时参数名称可能不同:
- 连接超时:connectTimeout
- 读取超时:readTimeout/socketTimeout
- 写入超时:writeTimeout
- 设置合理的超时时间可以防止程序长时间等待无响应的服务
- 对于生产环境,建议结合重试机制使用
选择哪种方式取决于你的项目使用的框架和库,现代Java项目通常倾向于使用OkHttp或Apache HttpClient等成熟的HTTP客户端库。

