import java.io.IOException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
public class SlidingWindowCrawlerWithProxy {
private static final String PROXY_HOST = "www.16yun.cn";
private static final int PROXY_PORT = 5445;
private static final String PROXY_USER = "16QMSOML";
private static final String PROXY_PASS = "280651";
private static final int WINDOW_SIZE = 60000; // 时间窗口大小(毫秒)
private static final int MAX_REQUESTS_PER_WINDOW = 100; // 每个时间窗口内的最大请求次数
private static final ConcurrentLinkedQueue<Long> requestTimes = new ConcurrentLinkedQueue<>();
public static void main(String[] args) {
String apiUrl = "https://api.example.com/data";
// 设置代理服务器
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", PROXY_HOST);
System.setProperty("http.proxyPort", String.valueOf(PROXY_PORT));
System.setProperty("https.proxyHost", PROXY_HOST);
System.setProperty("https.proxyPort", String.valueOf(PROXY_PORT));
// 设置代理认证
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyUser", PROXY_USER);
System.setProperty("http.proxyPassword", PROXY_PASS);
System.setProperty("https.proxyUser", PROXY_USER);
System.setProperty("https.proxyPassword", PROXY_PASS);
while (true) {
// 清理超出时间窗口的请求记录
long currentTime = System.currentTimeMillis();
while (!requestTimes.isEmpty() && currentTime - requestTimes.peek() > WINDOW_SIZE) {
requestTimes.poll();
}
// 检查是否达到请求频率限制
if (requestTimes.size() >= MAX_REQUESTS_PER_WINDOW) {
long delay = WINDOW_SIZE - (currentTime - requestTimes.peek());
System.out.println("Rate limit exceeded. Waiting for " + delay + " ms.");
try {
TimeUnit.MILLISECONDS.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 发起请求
try {
URL url = new URL(apiUrl);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
// 请求成功,处理响应数据
System.out.println("Data fetched successfully.");
} else {
System.out.println("Failed to fetch data. Response Code: " + responseCode);
}
} catch (IOException e) {
System.out.println("Error occurred: " + e.getMessage());
}
// 记录请求时间
requestTimes.add(System.currentTimeMillis());
}
}
}