public final class URLBuilder extends Object
Although this class supports various types of URLs, it exists primarily to
build HTTP and HTTPS URLs, and to be convertable to a java.net.URL
.
To that end, it assumes that URLs will follow the format
protocol://host:port/path?query
, where :port
is
optional.
If you omit the hostname, this class will build "relative" URLs, which are
useful for inserting into href
attributes. If you omit the
path, it will use the default path "/".
All public methods follow the Builder pattern, so that you can string calls together.
Constructor and Description |
---|
URLBuilder()
Creates a builder where the path is "/".
|
URLBuilder(String path)
Creates a builder that specifies an explicit path (which may or may
not contain hostname and protocol components).
|
URLBuilder(String protocol,
String host,
String path)
Creates a builder from basic components.
|
Modifier and Type | Method and Description |
---|---|
URLBuilder |
appendOptionalParameter(String name,
String value)
Appends a query parameter, escaping as needed.
|
URLBuilder |
appendParameter(String name,
String value)
Appends a query parameter, escaping as needed.
|
URLBuilder |
appendPath(String pathElement)
Appends an element to the path, escaping any reserved characters.
|
String |
toString()
Returns the string value of this URL.
|
public URLBuilder()
public URLBuilder(String path)
public URLBuilder(String protocol, String host, String path)
protocol
- The protocol, sans colon and separator (eg, "http",
not "http://"). If null
, will default
to HTTP.host
- The hostname, with optional port. May be
null
, to create local URLs (in which case the
protocol will be omitted).path
- The context path. This is considered an absolute path
from the host's root, so will be prepended with a '/'
if it is not already; null
or empty paths
will be replaced by "/". Since this path may contain
multiple slash-separated components, it will not be
URL-escaped; see appendPath(java.lang.String)
if you need to
escape path components.public URLBuilder appendPath(String pathElement)
public URLBuilder appendParameter(String name, String value)
null
value is treated as an empty string (so will appear as name=).public URLBuilder appendOptionalParameter(String name, String value)
null
, does not append anything.