diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRedirectStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRedirectStrategy.java index ca0b41f64d..747c7875fb 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRedirectStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRedirectStrategy.java @@ -185,9 +185,12 @@ protected URI createLocationURI(final String location) throws ProtocolException final String host = b.getHost(); if (host != null) { b.setHost(host.toLowerCase(Locale.ROOT)); - } - if (b.isPathEmpty()) { - b.setPathSegments(""); + // Only a location with an authority (an absolute URI or "//host") gets an empty path + // replaced with "/". A relative reference with an empty path ("?query" or + // "#fragment") keeps the path of the base URI. + if (b.isPathEmpty()) { + b.setPathSegments(""); + } } return b.build(); } catch (final URISyntaxException ex) { diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultRedirectStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultRedirectStrategy.java index 6617648b41..265e164ee2 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultRedirectStrategy.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultRedirectStrategy.java @@ -163,6 +163,28 @@ void testGetLocationUriRelative() throws Exception { Assertions.assertEquals(URI.create("http://localhost/stuff"), uri); } + @Test + void testGetLocationUriRelativeQueryOnly() throws Exception { + final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + final HttpClientContext context = HttpClientContext.create(); + final HttpGet httpget = new HttpGet("http://localhost/stuff/index.html?a=1"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + response.addHeader("Location", "?b=2"); + final URI uri = redirectStrategy.getLocationURI(httpget, response, context); + Assertions.assertEquals(URI.create("http://localhost/stuff/index.html?b=2"), uri); + } + + @Test + void testGetLocationUriFragmentOnly() throws Exception { + final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + final HttpClientContext context = HttpClientContext.create(); + final HttpGet httpget = new HttpGet("http://localhost/stuff/index.html?a=1"); + final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY, "Redirect"); + response.addHeader("Location", "#fragment"); + final URI uri = redirectStrategy.getLocationURI(httpget, response, context); + Assertions.assertEquals(URI.create("http://localhost/stuff/index.html?a=1#fragment"), uri); + } + @Test void testGetLocationUriRelativeWithFragment() throws Exception { final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();