在Java中,可以使用HttpURLConnection类来发送HTTP请求并设置超时时间。以下是一个示例,展示了如何设置连接超时和读取超时:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpTimeoutExample {
public static void main(String[] args) {
try {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置连接超时时间(单位:毫秒)
int connectionTimeout = 5000;
connection.setConnectTimeout(connectionTimeout);
// 设置读取超时时间(单位:毫秒)
int readTimeout = 5000;
connection.setReadTimeout(readTimeout);
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Content: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个示例中,我们设置了连接超时为5000毫秒(5秒)和读取超时为5000毫秒(5秒)。如果在这段时间内无法建立连接或读取数据,将抛出SocketTimeoutException异常。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。