Imagine you need to send the information about your payment in an online shop to a bank. It is known that the Internet connection is very unstable and the server often cannot process requests. Since the delivery of payment information is quite crucial, you decided to use retries in case of any errors.
Supplement the code below focusing on the line numbers 1, 2, 3, 4, 5, 6, 7. To understand the code better, read the comments and strings. You might also want to copy the code and try to examine it more closely in your local IDE.
public class HTTPInteractionExample {
private static final int MAX_TIMEOUT_MS = 10000; // 10000 ms = 10 seconds
private static final int MAX_RETRIES = 5;
private static final int WAIT_TIMEOUT_MS = 5000;
public static HttpResponse<String> sendData(HttpClient client, URI service, String jsonData)
throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(service)
// 1
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
// 2
}
public static HttpResponse<String> sendDataWithRetries(HttpClient client, URI service, String jsonData)
throws Exception {
int retry = 0;
while (...) { // 3
// 4
try {
// 5
if (response.statusCode() < 400) {
return response;
}
if (response.statusCode() >= 500) {
// 6
}
throw new Exception("Incorrect request, probably, we need to fix the code");
} catch (Exception e) {
System.out.println("An interaction error has occurred, will retry the request later");
}
try {
TimeUnit.MILLISECONDS.sleep(WAIT_TIMEOUT_MS); // waiting before the next retry
} catch (InterruptedException ignored) { }
}
throw new Exception("Cannot get the response after " + retry + " retries");
}
public static void main(String[] args) {
HttpClient httpClient = HttpClient.newHttpClient();
URI fakePostService = URI.create("https://jsonplaceholder.typicode.com/posts");
String payment = "{\"order\":\"1234\", \"price\":\"10000\"}";
try {
// 7
System.out.println(response.body());
} catch (Exception e) {
System.out.println("It's impossible to complete the action after several retries");
}
}
}