温馨提示×

java请求超时时间怎么实现

小亿
100
2024-01-14 02:57:02
栏目: 编程语言

在Java中,可以使用URLConnection或HttpClient来发送HTTP请求,并设置请求超时时间。

  1. 使用URLConnection:
URL url = new URL("http://example.com");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000); // 设置连接超时时间为5秒
connection.setReadTimeout(5000); // 设置读取数据超时时间为5秒

// 发送请求和处理响应...

  1. 使用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);

// 处理响应...

以上代码示例分别使用URLConnection和HttpClient来发送HTTP请求,并设置连接超时时间和读取数据超时时间为5秒。可以根据实际需要调整超时时间。

0