用java写一段每隔一分钟访问百度的请求,超过十分钟自动停止
时间: 2024-05-13 10:20:51 浏览: 73
```
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class BaiduRequester {
private static final String BAIDU_URL = "https://www.baidu.com/";
private static final int TIMEOUT = 5000;
private static final int INTERVAL = 60000;
private static final int MAX_TIME = 10;
private int count = 0;
private Timer timer;
public void start() {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
count++;
if (count > MAX_TIME) {
stop();
} else {
try {
URL url = new URL(BAIDU_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
System.out.println("Successfully accessed " + BAIDU_URL);
} else {
System.out.println("Failed to access " + BAIDU_URL + ", response code: " + responseCode);
}
connection.disconnect();
} catch (IOException e) {
System.out.println("Failed to access " + BAIDU_URL + ": " + e.getMessage());
}
}
}
}, 0, INTERVAL);
}
public void stop() {
if (timer != null) {
timer.cancel();
System.out.println("Stopped accessing " + BAIDU_URL);
}
}
public static void main(String[] args) {
BaiduRequester requester = new BaiduRequester();
requester.start();
}
}
```
使用Timer和TimerTask实现每隔一分钟访问百度一次,并且超过十分钟后自动停止访问。在每次访问时,使用Java的HttpURLConnection发送GET请求,最后输出访问结果。如果超过十分钟,调用stop方法停止定时器。
阅读全文