RFC 3986 conformance: revised and optimized `URIUtils#extractHost`

This commit is contained in:
Oleg Kalnichevski 2020-09-17 11:21:09 +02:00
parent 0524eed4b9
commit 6395fa7c79
2 changed files with 11 additions and 50 deletions

View File

@ -250,56 +250,17 @@ public class URIUtils {
if (uri == null) {
return null;
}
HttpHost target = null;
if (uri.isAbsolute()) {
int port = uri.getPort(); // may be overridden later
String host = uri.getHost();
if (host == null) { // normal parse failed; let's do it ourselves
// authority does not seem to care about the valid character-set for host names
host = uri.getAuthority();
if (host != null) {
// Strip off any leading user credentials
final int at = host.indexOf('@');
if (at >= 0) {
if (host.length() > at+1 ) {
host = host.substring(at+1);
} else {
host = null; // @ on its own
}
}
// Extract the port suffix, if present
if (host != null) {
final int colon = host.indexOf(':');
if (colon >= 0) {
final int pos = colon + 1;
int len = 0;
for (int i = pos; i < host.length(); i++) {
if (Character.isDigit(host.charAt(i))) {
len++;
} else {
break;
}
}
if (len > 0) {
try {
port = Integer.parseInt(host.substring(pos, pos + len));
} catch (final NumberFormatException ex) {
}
}
host = host.substring(0, colon);
}
}
}
}
final String scheme = uri.getScheme();
final URIBuilder uriBuilder = new URIBuilder(uri);
final String scheme = uriBuilder.getScheme();
final String host = uriBuilder.getHost();
final int port = uriBuilder.getPort();
if (!TextUtils.isBlank(host)) {
try {
target = new HttpHost(scheme, host, port);
return new HttpHost(scheme, host, port);
} catch (final IllegalArgumentException ignore) {
}
}
}
return target;
return null;
}
/**

View File

@ -230,9 +230,9 @@ public class TestURIUtils {
Assert.assertEquals(new HttpHost("localhost",8080),
URIUtils.extractHost(new URI("http://localhost:8080/;sessionid=stuff/abcd")));
Assert.assertEquals(new HttpHost("localhost",8080),
Assert.assertEquals(null,
URIUtils.extractHost(new URI("http://localhost:8080;sessionid=stuff/abcd")));
Assert.assertEquals(new HttpHost("localhost",-1),
Assert.assertEquals(null,
URIUtils.extractHost(new URI("http://localhost:;sessionid=stuff/abcd")));
Assert.assertEquals(null,
URIUtils.extractHost(new URI("http://:80/robots.txt")));