-
Notifications
You must be signed in to change notification settings - Fork 38.6k
Integrate Apache Http client with WebClient #24700
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
martin-tarjanyi
wants to merge
14
commits into
spring-projects:master
from
martin-tarjanyi:webclient_apache
Closed
Changes from 13 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
14a63db
Integrate Apache http client with WebClient
martin-tarjanyi 1bf43f0
Fix javadoc
martin-tarjanyi 85dd3b7
Minor code and doc polishment
martin-tarjanyi 78720fd
Merge remote-tracking branch 'remotes/origin/master' into webclient_a…
martin-tarjanyi df32d7f
Fix handling of multiple request cookies for apache http client
martin-tarjanyi 3a7f4ed
Conform to code style
martin-tarjanyi 7f8e1f2
Merge remote-tracking branch 'remotes/origin/master' into webclient_a…
martin-tarjanyi ac233bb
Rename Apache client components for consistency
martin-tarjanyi d33dc05
Polish HttpComponents WebClient implementation
martin-tarjanyi 1a92f3c
Re-add response cookie integration test for WebClient
martin-tarjanyi 58f8488
Use CookieStore to send cookies with HttpComponents client
martin-tarjanyi 3b032e2
Move response body stream handling to getBody method
martin-tarjanyi b5c2fa0
Pass content encoding and type to ReactiveEntityProducer
martin-tarjanyi f578f6e
Code review changes
martin-tarjanyi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
169 changes: 169 additions & 0 deletions
169
...main/java/org/springframework/http/client/reactive/HttpComponentsClientHttpConnector.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,169 @@ | ||
/* | ||
* Copyright 2002-2020 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. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.http.client.reactive; | ||
|
||
import java.net.URI; | ||
import java.nio.ByteBuffer; | ||
import java.util.function.Function; | ||
import java.util.function.Supplier; | ||
|
||
import org.apache.hc.client5.http.cookie.BasicCookieStore; | ||
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; | ||
import org.apache.hc.client5.http.impl.async.HttpAsyncClients; | ||
import org.apache.hc.client5.http.protocol.HttpClientContext; | ||
import org.apache.hc.core5.concurrent.FutureCallback; | ||
import org.apache.hc.core5.http.ContentType; | ||
import org.apache.hc.core5.http.HttpResponse; | ||
import org.apache.hc.core5.http.Message; | ||
import org.apache.hc.core5.http.nio.support.BasicRequestProducer; | ||
import org.apache.hc.core5.reactive.ReactiveEntityProducer; | ||
import org.apache.hc.core5.reactive.ReactiveResponseConsumer; | ||
import org.reactivestreams.Publisher; | ||
import reactor.core.publisher.Flux; | ||
import reactor.core.publisher.Mono; | ||
import reactor.core.publisher.MonoSink; | ||
|
||
import org.springframework.core.io.buffer.DataBufferFactory; | ||
import org.springframework.core.io.buffer.DefaultDataBufferFactory; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.http.HttpMethod; | ||
import org.springframework.lang.Nullable; | ||
|
||
/** | ||
* {@link ClientHttpConnector} implementation for the Apache HttpComponents HttpClient 5.x. | ||
* | ||
* @author Martin Tarjányi | ||
* @since 5.3 | ||
* @see <a href="https://hc.apache.org/index.html">Apache HttpComponents</a> | ||
*/ | ||
public class HttpComponentsClientHttpConnector implements ClientHttpConnector { | ||
|
||
private final CloseableHttpAsyncClient client; | ||
|
||
private final DataBufferFactory dataBufferFactory; | ||
|
||
private final Supplier<? extends HttpClientContext> contextSupplier; | ||
|
||
|
||
/** | ||
* Default constructor that creates and starts a new instance of {@link CloseableHttpAsyncClient}. | ||
*/ | ||
public HttpComponentsClientHttpConnector() { | ||
this(HttpAsyncClients.createDefault()); | ||
} | ||
|
||
/** | ||
* Constructor with a pre-configured {@link CloseableHttpAsyncClient} instance. | ||
* @param client the client to use | ||
*/ | ||
public HttpComponentsClientHttpConnector(CloseableHttpAsyncClient client) { | ||
this(client, HttpClientContext::create); | ||
} | ||
|
||
/** | ||
* Constructor with a pre-configured {@link CloseableHttpAsyncClient} instance | ||
* and a {@link HttpClientContext} supplier lambda which is called before each request | ||
* and passed to the client. | ||
* @param client the client to use | ||
* @param contextSupplier a {@link HttpClientContext} supplier | ||
*/ | ||
public HttpComponentsClientHttpConnector(CloseableHttpAsyncClient client, | ||
Supplier<? extends HttpClientContext> contextSupplier) { | ||
|
||
this.dataBufferFactory = new DefaultDataBufferFactory(); | ||
this.contextSupplier = contextSupplier; | ||
this.client = client; | ||
this.client.start(); | ||
} | ||
|
||
|
||
@Override | ||
public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri, | ||
Function<? super ClientHttpRequest, Mono<Void>> requestCallback) { | ||
|
||
HttpClientContext context = this.contextSupplier.get(); | ||
poutsma marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if (context.getCookieStore() == null) { | ||
context.setCookieStore(new BasicCookieStore()); | ||
} | ||
|
||
HttpComponentsClientHttpRequest request = new HttpComponentsClientHttpRequest(method, uri, | ||
context, this.dataBufferFactory); | ||
|
||
return requestCallback.apply(request).then(Mono.defer(() -> execute(request, context))); | ||
} | ||
|
||
private Mono<ClientHttpResponse> execute(HttpComponentsClientHttpRequest request, HttpClientContext context) { | ||
Flux<ByteBuffer> byteBufferFlux = request.getByteBufferFlux(); | ||
|
||
ReactiveEntityProducer reactiveEntityProducer = createReactiveEntityProducer(request, byteBufferFlux); | ||
|
||
BasicRequestProducer basicRequestProducer = new BasicRequestProducer(request.getHttpRequest(), | ||
reactiveEntityProducer); | ||
|
||
poutsma marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return Mono.<Message<HttpResponse, Publisher<ByteBuffer>>>create(sink -> { | ||
ReactiveResponseConsumer reactiveResponseConsumer = | ||
new ReactiveResponseConsumer(new MonoFutureCallbackAdapter<>(sink)); | ||
|
||
this.client.execute(basicRequestProducer, reactiveResponseConsumer, context, null); | ||
poutsma marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}).map(message -> new HttpComponentsClientHttpResponse(this.dataBufferFactory, message, context)); | ||
} | ||
|
||
@Nullable | ||
private ReactiveEntityProducer createReactiveEntityProducer(HttpComponentsClientHttpRequest request, | ||
poutsma marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@Nullable Flux<ByteBuffer> byteBufferFlux) { | ||
|
||
if (byteBufferFlux == null) { | ||
return null; | ||
} | ||
poutsma marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
String contentEncoding = request.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); | ||
|
||
ContentType contentType = null; | ||
|
||
if (request.getHeaders().getContentType() != null) { | ||
contentType = ContentType.parse(request.getHeaders().getContentType().toString()); | ||
} | ||
|
||
return new ReactiveEntityProducer(byteBufferFlux, request.getContentLength(), contentType, contentEncoding); | ||
} | ||
|
||
|
||
private static class MonoFutureCallbackAdapter<T> implements FutureCallback<T> { | ||
poutsma marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
private final MonoSink<T> sink; | ||
|
||
public MonoFutureCallbackAdapter(MonoSink<T> sink) { | ||
this.sink = sink; | ||
} | ||
|
||
@Override | ||
public void completed(T result) { | ||
this.sink.success(result); | ||
} | ||
|
||
@Override | ||
public void failed(Exception ex) { | ||
this.sink.error(ex); | ||
} | ||
|
||
@Override | ||
public void cancelled() { | ||
} | ||
} | ||
|
||
} |
152 changes: 152 additions & 0 deletions
152
...c/main/java/org/springframework/http/client/reactive/HttpComponentsClientHttpRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
/* | ||
* Copyright 2002-2020 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. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.http.client.reactive; | ||
|
||
import java.net.URI; | ||
import java.net.URISyntaxException; | ||
import java.nio.ByteBuffer; | ||
import java.util.Collection; | ||
|
||
import org.apache.hc.client5.http.cookie.CookieStore; | ||
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; | ||
import org.apache.hc.client5.http.protocol.HttpClientContext; | ||
import org.apache.hc.core5.http.HttpRequest; | ||
import org.apache.hc.core5.http.message.BasicHttpRequest; | ||
import org.reactivestreams.Publisher; | ||
import reactor.core.publisher.Flux; | ||
import reactor.core.publisher.Mono; | ||
|
||
import org.springframework.core.io.buffer.DataBuffer; | ||
import org.springframework.core.io.buffer.DataBufferFactory; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.http.HttpMethod; | ||
|
||
import static org.springframework.http.MediaType.ALL_VALUE; | ||
|
||
/** | ||
* {@link ClientHttpRequest} implementation for the Apache HttpComponents HttpClient 5.x. | ||
* | ||
* @author Martin Tarjányi | ||
* @since 5.3 | ||
* @see <a href="https://hc.apache.org/index.html">Apache HttpComponents</a> | ||
*/ | ||
class HttpComponentsClientHttpRequest extends AbstractClientHttpRequest { | ||
|
||
private final HttpRequest httpRequest; | ||
|
||
private final DataBufferFactory dataBufferFactory; | ||
|
||
private final HttpClientContext context; | ||
|
||
private Flux<ByteBuffer> byteBufferFlux; | ||
|
||
private long contentLength = -1; | ||
|
||
|
||
public HttpComponentsClientHttpRequest(HttpMethod method, URI uri, HttpClientContext context, | ||
DataBufferFactory dataBufferFactory) { | ||
|
||
this.context = context; | ||
this.httpRequest = new BasicHttpRequest(method.name(), uri); | ||
this.dataBufferFactory = dataBufferFactory; | ||
} | ||
|
||
|
||
@Override | ||
public HttpMethod getMethod() { | ||
return HttpMethod.resolve(this.httpRequest.getMethod()); | ||
} | ||
|
||
@Override | ||
public URI getURI() { | ||
try { | ||
return this.httpRequest.getUri(); | ||
} | ||
catch (URISyntaxException ex) { | ||
throw new IllegalArgumentException("Invalid URI syntax.", ex); | ||
} | ||
} | ||
|
||
@Override | ||
public DataBufferFactory bufferFactory() { | ||
return this.dataBufferFactory; | ||
} | ||
|
||
@Override | ||
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { | ||
return doCommit(() -> { | ||
this.byteBufferFlux = Flux.from(body).map(DataBuffer::asByteBuffer); | ||
return Mono.empty(); | ||
}); | ||
} | ||
|
||
@Override | ||
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { | ||
return writeWith(Flux.from(body).flatMap(p -> p)); | ||
} | ||
|
||
@Override | ||
public Mono<Void> setComplete() { | ||
return doCommit(); | ||
} | ||
|
||
@Override | ||
protected void applyHeaders() { | ||
HttpHeaders headers = getHeaders(); | ||
this.contentLength = headers.getContentLength(); | ||
|
||
headers.entrySet() | ||
.stream() | ||
.filter(entry -> !HttpHeaders.CONTENT_LENGTH.equals(entry.getKey())) | ||
.forEach(entry -> entry.getValue().forEach(v -> this.httpRequest.addHeader(entry.getKey(), v))); | ||
|
||
if (!this.httpRequest.containsHeader(HttpHeaders.ACCEPT)) { | ||
this.httpRequest.addHeader(HttpHeaders.ACCEPT, ALL_VALUE); | ||
} | ||
} | ||
|
||
@Override | ||
protected void applyCookies() { | ||
if (getCookies().isEmpty()) { | ||
return; | ||
} | ||
|
||
CookieStore cookieStore = this.context.getCookieStore(); | ||
|
||
getCookies().values() | ||
.stream() | ||
.flatMap(Collection::stream) | ||
.forEach(cookie -> { | ||
BasicClientCookie clientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue()); | ||
clientCookie.setDomain(getURI().getHost()); | ||
clientCookie.setPath(getURI().getPath()); | ||
cookieStore.addCookie(clientCookie); | ||
}); | ||
} | ||
|
||
public HttpRequest getHttpRequest() { | ||
return this.httpRequest; | ||
} | ||
|
||
public Flux<ByteBuffer> getByteBufferFlux() { | ||
return this.byteBufferFlux; | ||
} | ||
|
||
public long getContentLength() { | ||
return this.contentLength; | ||
} | ||
poutsma marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.