Implement retry in Java for http request
时间: 2024-03-29 07:35:27 浏览: 118
http请求的java实现
Sure, here's an example of how to implement retry in Java for an HTTP request using the Apache HttpClient library:
```java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
public class HttpRequestRetry {
private static final int MAX_RETRIES = 3;
public static void main(String[] args) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("https://www.example.com");
int retryCount = 0;
boolean success = false;
while (retryCount < MAX_RETRIES && !success) {
try {
httpClient.execute(httpGet, (HttpContext) null);
success = true;
} catch (IOException e) {
System.out.println("Request failed, retrying...");
retryCount++;
}
}
if (success) {
System.out.println("Request succeeded after " + retryCount + " retries.");
} else {
System.out.println("Request failed after " + retryCount + " retries.");
}
}
}
```
In this example, we create an `HttpClient` instance using the `HttpClientBuilder` class, and then create an `HttpGet` request object for the URL we want to retrieve. We then loop through the request up to a maximum number of retries (in this case, 3), attempting the request each time and catching any `IOException` that is thrown. If the request succeeds, we set the `success` flag to true and exit the loop. If the request fails after the maximum number of retries, we print a failure message.
阅读全文