HTTPCLIENT-1831: URIBuilder should not prepend a leading slash to relative URIs

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.5.x@1787739 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2017-03-20 12:26:39 +00:00
parent 44f8924b58
commit fe3a913e6b
2 changed files with 34 additions and 22 deletions

View File

@ -146,9 +146,9 @@ public class URIBuilder {
}
}
if (this.encodedPath != null) {
sb.append(normalizePath(this.encodedPath));
sb.append(normalizePath(this.encodedPath, sb.length() == 0));
} else if (this.path != null) {
sb.append(encodePath(normalizePath(this.path)));
sb.append(encodePath(normalizePath(this.path, sb.length() == 0)));
}
if (this.encodedQuery != null) {
sb.append("?").append(this.encodedQuery);
@ -166,6 +166,26 @@ public class URIBuilder {
return sb.toString();
}
private static String normalizePath(final String path, final boolean relative) {
String s = path;
if (TextUtils.isBlank(s)) {
return "";
}
int n = 0;
for (; n < s.length(); n++) {
if (s.charAt(n) != '/') {
break;
}
}
if (n > 1) {
s = s.substring(n - 1);
}
if (!relative && !s.startsWith("/")) {
s = "/" + s;
}
return s;
}
private void digestURI(final URI uri) {
this.scheme = uri.getScheme();
this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
@ -491,24 +511,4 @@ public class URIBuilder {
return buildString();
}
private static String normalizePath(final String path) {
String s = path;
if (TextUtils.isBlank(s)) {
return "";
}
int n = 0;
for (; n < s.length(); n++) {
if (s.charAt(n) != '/') {
break;
}
}
if (n > 1) {
s = s.substring(n - 1);
}
if (!s.startsWith("/")) {
s = "/" + s;
}
return s;
}
}

View File

@ -299,4 +299,16 @@ public class TestURIBuilder {
Assert.assertEquals("example.com", uri.getHost());
}
@Test
public void testRelativePath() throws Exception {
final URI uri = new URIBuilder("./mypath").build();
Assert.assertEquals(new URI("./mypath"), uri);
}
@Test
public void testRelativePathWithAuthority() throws Exception {
final URI uri = new URIBuilder("./mypath").setHost("somehost").setScheme("http").build();
Assert.assertEquals(new URI("http://somehost/./mypath"), uri);
}
}