Request: mechanism for making HttpRequest.Builder from HttpRequest
Craig Andrews
candrews at integralblue.com
Thu Oct 15 16:22:30 UTC 2020
Java's HttpClient relies on the builder pattern to produce immutable
objects on which actual operations are done. However, it currently lacks
a way to convert those working objects back to builders in order to
mutate them.
For example, I'd like to take a java.net.http.HttpRequest and change it;
for example, I'd like to add a header. The first approach that came to
my mind was to make the HttpRequest into a HttpRequest.Builder, add the
header, then build the builder, like this:
HttpRequest addHeader(final HttpRequest request, String name, String
value) {
return request.toBuilder().header(name, value).build();
}
However, there is no HttpRequest.toBuilder() method.
As a workaround, I wrote a "httpRequestToBuilder" method:
HttpRequest.Builder httpRequestToBuilder(final HttpRequest request) {
final HttpRequest.Builder builder = HttpRequest.newBuilder();
builder.expectContinue(request.expectContinue());
request.headers().map().forEach((name, values) -> values.forEach(value
-> builder.header(name, value)));
builder.method(request.method(),
request.bodyPublisher().orElseGet(BodyPublishers::noBody));
request.timeout().ifPresent(builder::timeout);
builder.uri(request.uri());
request.version().ifPresent(builder::version);
return builder;
}
I think we can all agree that it's best for people to not have to write,
test, and maintain such functions, especially as Java's HttpClient
evolves in the future.
Will this group entertain the suggestion to add a toBuilder() method
HttpRequest, or equivalent functionality?
I believe such a toBuilder() method would be helpful on
java.net.http.HttpClient as well.
Thank you,
~Craig
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 195 bytes
Desc: OpenPGP digital signature
URL: <https://mail.openjdk.java.net/pipermail/net-dev/attachments/20201015/343a7aab/signature.asc>
More information about the net-dev
mailing list