Handle HTTP response codes when retrieving data from remote endpoints

Closes #20895
This commit is contained in:
Alexander Schwartz 2023-06-09 18:27:57 +02:00 committed by Marek Posolda
parent 475b4fa05b
commit 9425432f2c
2 changed files with 9 additions and 2 deletions

View file

@ -54,7 +54,7 @@ public interface HttpClientProvider extends Provider {
*
* @param uri
* @return response stream, you must close this stream or leaks will happen
* @throws IOException
* @throws IOException On network errors, no content being returned or a non-2xx HTTP status code
*/
public InputStream get(String uri) throws IOException;
}

View file

@ -110,8 +110,15 @@ public class DefaultHttpClientFactory implements HttpClientFactory {
public InputStream get(String uri) throws IOException {
HttpGet request = new HttpGet(uri);
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity == null) return null;
if (statusCode < 200 || statusCode >= 300) {
EntityUtils.consumeQuietly(entity);
throw new IOException("Unexpected HTTP status code " + response.getStatusLine().getStatusCode() + " when expecting 2xx");
}
if (entity == null) {
throw new IOException("No content returned from HTTP call");
}
return entity.getContent();
}