我们使用java.util.Timer和java.util.TimerTask来创建定时任务。在run()方法中,我们调用了一个HTTP接口,并输出了接口的响应结果。例如在main()方法中,我们创建了一个定时器和定时任务,并通过timer.schedule(task, delay, period)方法来设置任务的延迟执行时间和重复执行间隔。在上述示例中,我们将任务延迟1秒后开始执行,然后每隔5秒执行一次。
import java.util.Timer;
import java.util.TimerTask;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpInterfaceCaller {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
try {
URL url = new URL("http://xxxxxxx.com/xxx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.schedule(task, 1000, 5000);
}
}
请注意,上述示例中的HTTP接口调用是在主线程中执行的。如果需要在后台线程中执行,可以考虑使用java.util.concurrent.ScheduledExecutorService来代替java.util.Timer和java.util.TimerTask。