import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class HtmlOutputLimiter {
private final int maxRetries;
private final int retryDelayMillis;
private final Map<String, Integer> retryCounts = new HashMap<>();
public HtmlOutputLimiter(int maxRetries, int retryDelayMillis) {
this.maxRetries = maxRetries;
this.retryDelayMillis = retryDelayDelayMillis;
}
public String getHtml(String url) throws IOException {
int retryCount = 0;
while (retryCount <= maxRetries) {
try {
return fetchHtml(url);
} catch (IOException e) {
retryCount++;
if (retryCount > maxRetries) {
throw e; // Re-throw if max retries reached
}
try {
Thread.sleep(retryDelayMillis); // Wait before retrying
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Restore interrupted status
throw new IOException("Retry interrupted", ie);
}
}
}
return ""; // Should not reach here
}
private String fetchHtml(String url) throws IOException {
URL htmlUrl = new URL(url);
URLConnection connection = htmlUrl.openConnection();
connection.setConnectTimeout(5000); // Set connect timeout
connection.setReadTimeout(10000); // Set read timeout
String html = connection.getInputStream().toString();
return html;
}
public void incrementRetryCount(String url) {
retryCounts.put(url, (retryCounts.getOrDefault(url, 0) + 1));
}
public static void main(String[] args) throws IOException {
HtmlOutputLimiter limiter = new HtmlOutputLimiter(3, 1000); // 3 retries, 1 second delay
try {
String html = limiter.getHtml("https://www.example.com");
System.out.println(html.substring(0, 200) + "..."); // Print first 200 chars.
} catch (IOException e) {
System.err.println("Failed to fetch HTML after multiple retries: " + e.getMessage());
}
}
}
Add your comment