public final class HttpUrl extends Object
http
or https
. Use this
class to compose and decompose Internet addresses. For example, this code will compose and print
a URL for Google search:
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegment("search")
.addQueryParameter("q", "polar bears")
.build();
System.out.println(url);
which prints:
https://www.google.com/search?q=polar%20bears
As another example, this code prints the human-readable query parameters of a Twitter search:
HttpUrl url = HttpUrl.parse("https://twitter.com/search?q=cute%20%23puppies&f=images");
for (int i = 0, size = url.querySize(); i < size; i++) {
System.out.println(url.queryParameterName(i) + ": " + url.queryParameterValue(i));
}
which prints:
q: cute #puppies
f: images
In addition to composing URLs from their component parts and decomposing URLs into their
component parts, this class implements relative URL resolution: what address you'd reach by
clicking a relative link on a specified page. For example:
HttpUrl base = HttpUrl.parse("https://www.youtube.com/user/WatchTheDaily/videos");
HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc");
System.out.println(link);
which prints:
https://www.youtube.com/watch?v=cbP2N1BQdYc
mailto
, file
, ftp
), this class only supports http
and https
. Use java.net.URI
for
URLs with arbitrary schemes.
""
if absent. This class
offers no mechanism to differentiate empty from absent. Neither of these components are popular
in practice. Typically HTTP applications use other mechanisms for user identification and
authentication.
square.com
or localhost
, an IPv4 address like 192.168.0.1
, or an IPv6
address like ::1
.
Usually a webserver is reachable with multiple identifiers: its IP addresses, registered
domain names, and even localhost
when connecting from the server itself. Each of a
webserver's names is a distinct URL and they are not interchangeable. For example, even if
http://square.github.io/dagger
and http://google.github.io/dagger
are served by
the same IP address, the two URLs identify different resources.
cute #puppies
is encoded as cute%20%23puppies
when used as a query
parameter value.
🍩
) with its UTF-8 hex bytes (like
%F0%9F%8D%A9
). This approach works for whitespace characters, control characters,
non-ASCII characters, and characters that already have another meaning in a particular context.
Percent encoding is used in every URL component except for the hostname. But the set of
characters that need to be encoded is different for each component. For example, the path
component must escape all of its ?
characters, otherwise it could be interpreted as the
start of the URL's query. But within the query and fragment components, the ?
character
doesn't delimit anything and doesn't need to be escaped.
HttpUrl url = HttpUrl.parse("http://who-let-the-dogs.out").newBuilder()
.addPathSegment("_Who?_")
.query("_Who?_")
.fragment("_Who?_")
.build();
System.out.println(url);
This prints:
http://who-let-the-dogs.out/_Who%3F_?_Who?_#_Who?_
When parsing URLs that lack percent encoding where it is required, this class will percent encode
the offending characters.
In order to avoid confusion and discourage phishing attacks,
IDNA Mapping transforms names to avoid
confusing characters. This includes basic case folding: transforming shouting SQUARE.COM
into cool and casual square.com
. It also handles more exotic characters. For example, the
Unicode trademark sign (™) could be confused for the letters "TM" in http://ho™mail.com
.
To mitigate this, the single character (™) maps to the string (tm). There is similar policy for
all of the 1.1 million Unicode code points. Note that some code points such as "🍩" are
not mapped and cannot be used in a hostname.
Punycode converts a Unicode string to an ASCII
string to make international domain names work everywhere. For example, "σ" encodes as
"xn--4xa". The encoded string is not human readable, but can be used with classes like InetAddress
to establish connections.
java.net.URL
and java.net.URI
. We offer a new URL
model to address problems that the others don't.
java.net.URL
considers the following two URLs
equal, and the equals()
method between them returns true:
java.net.URL
unusable for many things. It shouldn't be used as a Map
key or in a Set
. Doing so is both inefficient because equality may
require a DNS lookup, and incorrect because unequal URLs may be equal because of how they are
hosted.
java.net.URI
disagrees:
:80
) and the absent trailing slash (/
)
cause URI to bucket the two URLs separately. This harms URI's usefulness in collections. Any
application that stores information-per-URL will need to either canonicalize manually, or suffer
unnecessary redundancy for such URLs.
Because they don't attempt canonical form, these classes are surprisingly difficult to use securely. Suppose you're building a webservice that checks that incoming paths are prefixed "/static/images/" before serving the corresponding assets from the filesystem.
String attack = "http://example.com/static/images/../../../../../etc/passwd";
System.out.println(new URL(attack).getPath());
System.out.println(new URI(attack).getPath());
System.out.println(HttpUrl.parse(attack).path());
By canonicalizing the input paths, they are complicit in directory traversal attacks. Code that
checks only the path prefix may suffer!
/static/images/../../../../../etc/passwd
/static/images/../../../../../etc/passwd
/etc/passwd
java.net.URI
class is strict around what URLs it accepts. It rejects URLs like
"http://example.com/abc|def" because the '|' character is unsupported. This class is more
forgiving: it will automatically percent-encode the '|', yielding "http://example.com/abc%7Cdef".
This kind behavior is consistent with web browsers. HttpUrl
prefers consistency with
major web browsers over consistency with obsolete specifications.
StringBuilder
to assemble these components is cumbersome: do '+'
characters get silently replaced with spaces? If a query parameter contains a '&', does that
get escaped? By offering methods to read and write individual query parameters directly,
application developers are saved from the hassles of encoding and decoding.
Instances of HttpUrl
are well-formed and always have a scheme, host, and path. With
java.net.URL
it's possible to create an awkward URL like http:/
with scheme and
path but no hostname. Building APIs that consume such malformed values is difficult!
This class has a modern API. It avoids punitive checked exceptions: parse()
returns null if the input is an invalid URL. You can even be explicit about whether each
component has been encoded already.
Modifier and Type | Class and Description |
---|---|
static class |
HttpUrl.Builder |
Modifier and Type | Method and Description |
---|---|
static int |
defaultPort(String scheme)
Returns 80 if
scheme.equals("http") , 443 if scheme.equals("https") and -1
otherwise. |
String |
encodedFragment() |
String |
encodedPassword()
Returns the password, or an empty string if none is set.
|
String |
encodedPath()
Returns the entire path of this URL, encoded for use in HTTP resource resolution.
|
List<String> |
encodedPathSegments() |
String |
encodedQuery()
Returns the query of this URL, encoded for use in HTTP resource resolution.
|
String |
encodedUsername()
Returns the username, or an empty string if none is set.
|
boolean |
equals(Object o) |
String |
fragment() |
static HttpUrl |
get(URI uri) |
static HttpUrl |
get(URL url)
|
int |
hashCode() |
String |
host()
Returns the host address suitable for use with
InetAddress.getAllByName(String) . |
boolean |
isHttps() |
HttpUrl.Builder |
newBuilder() |
static HttpUrl |
parse(String url)
Returns a new
HttpUrl representing url if it is a well-formed HTTP or HTTPS
URL, or null if it isn't. |
String |
password()
Returns the decoded password, or an empty string if none is present.
|
List<String> |
pathSegments() |
int |
pathSize() |
int |
port()
Returns the explicitly-specified port if one was provided, or the default port for this URL's
scheme.
|
String |
query() |
String |
queryParameter(String name)
Returns the first query parameter named
name decoded using UTF-8, or null if there is
no such query parameter. |
String |
queryParameterName(int index) |
Set<String> |
queryParameterNames() |
String |
queryParameterValue(int index) |
List<String> |
queryParameterValues(String name) |
int |
querySize() |
HttpUrl |
resolve(String link)
Returns the URL that would be retrieved by following
link from this URL. |
String |
scheme()
Returns either "http" or "https".
|
String |
toString() |
URI |
uri()
Returns this URL as a
java.net.URI . |
URL |
url()
Returns this URL as a
java.net.URL . |
String |
username() |
public URL url()
java.net.URL
.public URI uri()
java.net.URI
. Because URI
forbids certain characters
like [
and |
, the returned URI may escape more characters than this URL.
This method throws an unchecked IllegalStateException
if it cannot be converted to a
URI even after escaping forbidden characters. In particular, URLs that contain malformed
percent escapes like http://host/%xx
will trigger this exception.
public String scheme()
public boolean isHttps()
public String encodedUsername()
public String username()
public String encodedPassword()
public String password()
public String host()
InetAddress.getAllByName(String)
. May
be:
android.com
.
127.0.0.1
.
::1
. Note that there are no square braces.
xn--n3h.net
.
public int port()
https://square.com:8443/
and 443 for https://square.com/
. The result is in [1..65535]
.public static int defaultPort(String scheme)
scheme.equals("http")
, 443 if scheme.equals("https")
and -1
otherwise.public int pathSize()
public String encodedPath()
/
.public String encodedQuery()
public String query()
public int querySize()
public String queryParameter(String name)
name
decoded using UTF-8, or null if there is
no such query parameter.public String queryParameterName(int index)
public String queryParameterValue(int index)
public String encodedFragment()
public String fragment()
public HttpUrl resolve(String link)
link
from this URL.public HttpUrl.Builder newBuilder()
public static HttpUrl parse(String url)
HttpUrl
representing url
if it is a well-formed HTTP or HTTPS
URL, or null if it isn't.Copyright © 2016. All Rights Reserved.