Support of HTTP persistent connections for JDK client
Prior to this commit, HTTP clients relying on the JDK HTTP client would not properly reuse existing TCP connections (i.e. HTTP 1.1 persisten connection). The SimpleClientHttpResponse would close the actual connection once the response is handled. As explained in the JDK documentation (http://docs.oracle.com/javase/8/docs/technotes/guides/net/http-keepalive.html) HTTP clients should do the following to allow resource reuse: * consume the whole HTTP response content * close the response inputstream once done This commit makes sure that the response content is totally drained and then the stream closed (and not the connection). Issue: SPR-14040
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2014 the original author or authors.
|
||||
* Copyright 2002-2016 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.
|
||||
@@ -21,6 +21,7 @@ import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
@@ -29,6 +30,7 @@ import org.springframework.util.StringUtils;
|
||||
* {@link SimpleStreamingClientHttpRequest#execute()}.
|
||||
*
|
||||
* @author Arjen Poutsma
|
||||
* @author Brian Clozel
|
||||
* @since 3.0
|
||||
*/
|
||||
final class SimpleClientHttpResponse extends AbstractClientHttpResponse {
|
||||
@@ -37,6 +39,8 @@ final class SimpleClientHttpResponse extends AbstractClientHttpResponse {
|
||||
|
||||
private HttpHeaders headers;
|
||||
|
||||
private InputStream responseStream;
|
||||
|
||||
|
||||
SimpleClientHttpResponse(HttpURLConnection connection) {
|
||||
this.connection = connection;
|
||||
@@ -78,12 +82,19 @@ final class SimpleClientHttpResponse extends AbstractClientHttpResponse {
|
||||
@Override
|
||||
public InputStream getBody() throws IOException {
|
||||
InputStream errorStream = this.connection.getErrorStream();
|
||||
return (errorStream != null ? errorStream : this.connection.getInputStream());
|
||||
this.responseStream = (errorStream != null ? errorStream : this.connection.getInputStream());
|
||||
return this.responseStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
this.connection.disconnect();
|
||||
if (this.responseStream != null) {
|
||||
try {
|
||||
StreamUtils.drain(this.responseStream);
|
||||
this.responseStream.close();
|
||||
}
|
||||
catch (IOException e) { }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user