How to implement timeout for Java requests?
In Java, you can use URLConnection or HttpClient to send HTTP requests and set request timeout.
- Utilize URLConnection:
URL url = new URL("http://example.com");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000); // 设置连接超时时间为5秒
connection.setReadTimeout(5000); // 设置读取数据超时时间为5秒
// 发送请求和处理响应...
- Utilizing HttpClient:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpParams params = httpClient.getParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // 设置连接超时时间为5秒
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); // 设置读取数据超时时间为5秒
HttpGet httpGet = new HttpGet("http://example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
// 处理响应...
The above code examples demonstrate using URLConnection and HttpClient to send HTTP requests, setting the connection timeout and data read timeout to 5 seconds. The timeout values can be adjusted according to actual needs.