在Java中,您可以使用java.net.HttpURLConnection
或者java.net.URL
类来设置HTTP请求的超时。以下是两种方法的示例:
方法1:使用 HttpURLConnection
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置连接超时(单位:毫秒)
connection.setConnectTimeout(5000);
// 设置读取超时(单位:毫秒)
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法2:使用 URL
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置连接超时(单位:毫秒)
connection.setConnectTimeout(5000);
// 设置读取超时(单位:毫秒)
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这两个示例中,我们将连接超时和读取超时都设置为5000毫秒(5秒)。您可以根据需要调整这些值。