阅读量:2
在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秒)。您可以根据需要调整这些值。
以上就是关于“java http如何设置超时”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm