HTTPCLIENT-1960: URIBuilder incorrect handling of multiple leading slashes in path component

This commit is contained in:
Oleg Kalnichevski 2019-01-12 17:02:13 +01:00
parent 024f692df3
commit 8c04c6ae5e
4 changed files with 35 additions and 12 deletions

View File

@ -171,15 +171,6 @@ public class URIBuilder {
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;
}

View File

@ -147,8 +147,20 @@ public class URIUtils {
if (dropFragment) {
uribuilder.setFragment(null);
}
if (TextUtils.isEmpty(uribuilder.getPath())) {
final String path = uribuilder.getPath();
if (TextUtils.isEmpty(path)) {
uribuilder.setPath("/");
} else {
final StringBuilder buf = new StringBuilder(path.length());
boolean foundSlash = false;
for (int i = 0; i < path.length(); i++) {
final char ch = path.charAt(i);
if (ch != '/' || !foundSlash) {
buf.append(ch);
}
foundSlash = ch == '/';
}
uribuilder.setPath(buf.toString());
}
return uribuilder.build();
}

View File

@ -36,6 +36,7 @@ import java.util.List;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
@ -328,4 +329,23 @@ public class TestURIBuilder {
Assert.assertEquals(new URI("http://somehost/./mypath"), uri);
}
@Test
public void testMultipleLeadingPathSlashes() throws Exception {
final URI uri = new URIBuilder()
.setScheme("ftp")
.setHost("somehost")
.setPath("//blah//blah")
.build();
Assert.assertThat(uri, CoreMatchers.equalTo(URI.create("ftp://somehost//blah//blah")));
}
@Test
public void testPathNoLeadingSlash() throws Exception {
final URI uri = new URIBuilder()
.setScheme("ftp")
.setPath("blah")
.build();
Assert.assertThat(uri, CoreMatchers.equalTo(URI.create("ftp:/blah")));
}
}

View File

@ -51,8 +51,8 @@ public class TestURIUtils {
URI.create("http://thishost/stuff"), null).toString());
Assert.assertEquals("/", URIUtils.rewriteURI(
URI.create("http://thishost//"), null).toString());
Assert.assertEquals("/stuff///morestuff", URIUtils.rewriteURI(
URI.create("http://thishost//stuff///morestuff"), null).toString());
Assert.assertEquals("/stuff/morestuff", URIUtils.rewriteURI(
URI.create("http://thishost//stuff/morestuff"), null).toString());
Assert.assertEquals("http://thathost/stuff", URIUtils.rewriteURI(
URI.create("http://thishost/stuff#crap"), target, true).toString());
Assert.assertEquals("http://thathost/stuff#crap", URIUtils.rewriteURI(