diff --git a/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java b/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java index febe0f5cb..eb84ab41c 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java @@ -207,7 +207,7 @@ public URIBuilder setCharset(final Charset charset) { * Sets the encoding policy for this {@link URIBuilder}. * The encoding policy determines how URI components (e.g., query, fragment) are * percent-encoded when building the URI string. If not set, the default policy - * is {@link EncodingPolicy#RFC_3986}. + * is {@link EncodingPolicy#ALL_RESERVED}. * * @param encodingPolicy the encoding policy to apply, or {@code null} to reset * to the default ({@link EncodingPolicy#ALL_RESERVED}) @@ -215,7 +215,7 @@ public URIBuilder setCharset(final Charset charset) { * @since 5.4 */ public URIBuilder setEncodingPolicy(final EncodingPolicy encodingPolicy) { - this.encodingPolicy = encodingPolicy; + this.encodingPolicy = encodingPolicy != null ? encodingPolicy : EncodingPolicy.ALL_RESERVED; return this; } diff --git a/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIBuilder.java b/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIBuilder.java index 3483309a3..42d0f00e2 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIBuilder.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIBuilder.java @@ -976,6 +976,39 @@ void testSetPlusAsBlank() throws Exception { Assertions.assertEquals("hello world", params.get(0).getValue()); } + @Test + void testDefaultEncodingPolicy() throws Exception { + final URIBuilder builder = new URIBuilder() + .setScheme("http") + .setHost("example.com") + .setPath("/a:b") + .addParameter("key", "a/b") + .setFragment("a/b"); + final URI expected = new URI("http://example.com/a%3Ab?key=a%2Fb#a%2Fb"); + + Assertions.assertEquals(expected, builder.build()); + builder.setEncodingPolicy(URIBuilder.EncodingPolicy.ALL_RESERVED); + Assertions.assertEquals(expected, builder.build()); + builder.setEncodingPolicy(null); + Assertions.assertEquals(expected, builder.build()); + } + + @Test + void testResetEncodingPolicy() throws Exception { + final URIBuilder builder = new URIBuilder() + .setScheme("http") + .setUserInfo("user!") + .setHost("example.com") + .setPath("/a:b") + .setCustomQuery("a/b") + .setFragment("a/b") + .setEncodingPolicy(URIBuilder.EncodingPolicy.RFC_3986); + + Assertions.assertEquals(new URI("http://user!@example.com/a:b?a/b#a/b"), builder.build()); + Assertions.assertSame(builder, builder.setEncodingPolicy(null)); + Assertions.assertEquals(new URI("http://user%21@example.com/a%3Ab?a%2Fb#a%2Fb"), builder.build()); + } + @Test void testCustomQueryEncoding() throws Exception { final String query = "query param:!@/?\"";