Skip to content

Commit

Permalink
Drain JDK HTTP client response body in all cases
Browse files Browse the repository at this point in the history
Prior to this commit, when using the `SimpleClientHttpRequestFactory`
as a driver for `RestTemplate`, the HTTP response body would only be
drained if there was an attempt to read it in the first place.

This commit ensures that, even if there's no attempt at reading the
response body, it is properly drained when the response is closed to
make sure that the connection is released in a proper state and can be
put back in the connection pool for reuse.

Issue: SPR-17181
  • Loading branch information
bclozel committed Aug 15, 2018
1 parent 432cdd7 commit 23fc6f6
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
Expand Up @@ -91,14 +91,15 @@ public InputStream getBody() throws IOException {

@Override
public void close() {
if (this.responseStream != null) {
try {
StreamUtils.drain(this.responseStream);
this.responseStream.close();
}
catch (Exception ex) {
// ignore
try {
if (this.responseStream == null) {
getBody();
}
StreamUtils.drain(this.responseStream);
this.responseStream.close();
}
catch (Exception ex) {
// ignore
}
}

Expand Down
Expand Up @@ -135,7 +135,7 @@ public void multipleWrites() throws Exception {

@Test(expected = UnsupportedOperationException.class)
public void headersAfterExecute() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST);

request.getHeaders().add("MyHeader", "value");
byte[] body = "Hello World".getBytes("UTF-8");
Expand Down
Expand Up @@ -106,6 +106,18 @@ public void shouldNotDrainWhenErrorStreamClosed() throws Exception {
verify(is).close();
}

@Test // SPR-17181
public void shouldDrainResponseEvenIfResponseNotRead() throws Exception {
TestByteArrayInputStream is = new TestByteArrayInputStream("SpringSpring".getBytes(StandardCharsets.UTF_8));
given(this.connection.getErrorStream()).willReturn(null);
given(this.connection.getInputStream()).willReturn(is);

this.response.close();
assertThat(is.available(), is(0));
assertTrue(is.isClosed());
verify(this.connection, never()).disconnect();
}


private static class TestByteArrayInputStream extends ByteArrayInputStream {

Expand Down

0 comments on commit 23fc6f6

Please sign in to comment.