Skip to content

Commit

Permalink
Use timeout for JdkClientHttpRequest response retrieval
Browse files Browse the repository at this point in the history
This commit ensures that, in JdkClientHttpRequest, the response is
obtained  using a timeout, instead of blocking indefinitely.

Closes gh-31911
  • Loading branch information
poutsma committed Jan 10, 2024
1 parent c440510 commit 49d3ec5
Showing 1 changed file with 32 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -28,8 +28,11 @@
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
Expand Down Expand Up @@ -90,16 +93,41 @@ public URI getURI() {
protected ClientHttpResponse executeInternal(HttpHeaders headers, @Nullable Body body) throws IOException {
try {
HttpRequest request = buildRequest(headers, body);
HttpResponse<InputStream> response =
this.httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
HttpResponse<InputStream> response;
if (this.timeout != null) {
response = this.httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
.get(this.timeout.toMillis(), TimeUnit.MILLISECONDS);
}
else {
response = this.httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
}
return new JdkClientHttpResponse(response);
}
catch (UncheckedIOException ex) {
throw ex.getCause();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IOException("Could not send request: " + ex.getMessage(), ex);
throw new IOException("Request was interrupted: " + ex.getMessage(), ex);
}
catch (ExecutionException ex) {
Throwable cause = ex.getCause();

if (cause instanceof UncheckedIOException uioEx) {
throw uioEx.getCause();
}
if (cause instanceof RuntimeException rtEx) {
throw rtEx;
}
else if (cause instanceof IOException ioEx) {
throw ioEx;
}
else {
throw new IOException(cause.getMessage(), cause);
}
}
catch (TimeoutException ex) {
throw new IOException("Request timed out: " + ex.getMessage(), ex);
}
}

Expand Down

0 comments on commit 49d3ec5

Please sign in to comment.