java.net

Class URL

Implemented Interfaces:
Serializable

public final class URL
extends Object
implements Serializable

This final class represents an Internet Uniform Resource Locator (URL). For details on the syntax of URL's and what they can be used for, refer to RFC 1738, available from http://ds.internic.net/rfcs/rfc1738.txt

There are a great many protocols supported by URL's such as "http", "ftp", and "file". This object can handle any arbitrary URL for which a URLStreamHandler object can be written. Default protocol handlers are provided for the "http" and "ftp" protocols. Additional protocols handler implementations may be provided in the future. In any case, an application or applet can install its own protocol handlers that can be "chained" with other protocol hanlders in the system to extend the base functionality provided with this class. (Note, however, that unsigned applets cannot access properties by default or install their own protocol handlers).

This chaining is done via the system property java.protocol.handler.pkgs If this property is set, it is assumed to be a "|" separated list of package names in which to attempt locating protocol handlers. The protocol handler is searched for by appending the string ".<protocol>.Handler" to each packed in the list until a hander is found. If a protocol handler is not found in this list of packages, or if the property does not exist, then the default protocol handler of "gnu.java.net.<protocol>.Handler" is tried. If this is unsuccessful, a MalformedURLException is thrown.

All of the constructor methods of URL attempt to load a protocol handler and so any needed protocol handlers must be installed when the URL is constructed.

Here is an example of how URL searches for protocol handlers. Assume the value of java.protocol.handler.pkgs is "com.foo|com.bar" and the URL is "news://comp.lang.java.programmer". URL would looking the following places for protocol handlers:

 com.foo.news.Handler
 com.bar.news.Handler
 gnu.java.net.news.Handler
 

If the protocol handler is not found in any of those locations, a MalformedURLException would be thrown.

Please note that a protocol handler must be a subclass of URLStreamHandler.

Normally, this class caches protocol handlers. Once it finds a handler for a particular protocol, it never tries to look up a new handler again. However, if the system property gnu.java.net.nocache_protocol_handlers is set, then this caching behavior is disabled. This property is specific to this implementation. Sun's JDK may or may not do protocol caching, but it almost certainly does not examine this property.

Please also note that an application can install its own factory for loading protocol handlers (see setURLStreamHandlerFactory). If this is done, then the above information is superseded and the behavior of this class in loading protocol handlers is dependent on that factory.

See Also:
URLStreamHandler, Serialized Form

Constructor Summary

URL(String spec)
Initializes a URL from a complete string specification such as "http://www.urbanophile.com/arenn/".
URL(String protocol, String host, int port, String file)
Constructs a URL and loads a protocol handler for the values passed as arguments.
URL(String protocol, String host, int port, String file, URLStreamHandler ph)
This method initializes a new instance of URL with the specified protocol, host, port, and file.
URL(String protocol, String host, String file)
Constructs a URL and loads a protocol handler for the values passed in as arugments.
URL(URL context, String spec)
This method parses a String representation of a URL within the context of an existing URL.
URL(URL context, String spec, URLStreamHandler ph)
Creates an URL from given arguments This method parses a String representation of a URL within the context of an existing URL.

Method Summary

boolean
equals(Object obj)
Test another URL for equality with this one.
String
getAuthority()
Returns the authority of the URL
Object
getContent()
Returns the contents of this URL as an object by first opening a connection, then calling the getContent() method against the connection
Object
getContent(Class<T>[] classes)
Gets the contents of this URL
int
getDefaultPort()
Returns the default port of the URL.
String
getFile()
Returns the file portion of the URL.
String
getHost()
Returns the host of the URL
String
getPath()
Returns the path of the URL.
int
getPort()
Returns the port number of this URL or -1 if the default port number is being used.
String
getProtocol()
Returns the protocol of the URL
String
getQuery()
Returns the query of the URL.
String
getRef()
Returns the ref (sometimes called the "# reference" or "anchor") portion of the URL.
String
getUserInfo()
Returns the user information of the URL.
int
hashCode()
Returns a hashcode computed by the URLStreamHandler of this URL
URLConnection
openConnection()
Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
InputStream
openStream()
Opens a connection to this URL and returns an InputStream for reading from that connection
boolean
sameFile(URL url)
Tests whether or not another URL refers to the same "file" as this one.
protected void
set(String protocol, String host, int port, String file, String ref)
Sets the specified fields of the URL.
protected void
set(String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref)
Sets the specified fields of the URL.
static void
setURLStreamHandlerFactory(URLStreamHandlerFactory fac)
Sets the URLStreamHandlerFactory for this class.
String
toExternalForm()
Returns a String representing this URL.
String
toString()
Returns a String representing this URL.
URI
toURI()
Returns the equivalent URI object for this URL.

Methods inherited from class java.lang.Object

clone, equals, extends Object> getClass, finalize, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Details

URL

public URL(String spec)
            throws MalformedURLException
Initializes a URL from a complete string specification such as "http://www.urbanophile.com/arenn/". First the protocol name is parsed out of the string. Then a handler is located for that protocol and the parseURL() method of that protocol handler is used to parse the remaining fields.
Parameters:
spec - The complete String representation of a URL
Throws:
MalformedURLException - If a protocol handler cannot be found or the URL cannot be parsed

URL

public URL(String protocol,
           String host,
           int port,
           String file)
            throws MalformedURLException
Constructs a URL and loads a protocol handler for the values passed as arguments.
Parameters:
protocol - The protocol for this URL ("http", "ftp", etc)
host - The hostname or IP address to connect to
port - The port number to use, or -1 to use the protocol's default port
file - The "file" portion of the URL.
Throws:
MalformedURLException - If a protocol handler cannot be loaded or a parse error occurs.

URL

public URL(String protocol,
           String host,
           int port,
           String file,
           URLStreamHandler ph)
            throws MalformedURLException
This method initializes a new instance of URL with the specified protocol, host, port, and file. Additionally, this method allows the caller to specify a protocol handler to use instead of the default. If this handler is specified, the caller must have the "specifyStreamHandler" permission (see NetPermission) or a SecurityException will be thrown.
Parameters:
protocol - The protocol for this URL ("http", "ftp", etc)
host - The hostname or IP address to connect to
port - The port number to use, or -1 to use the protocol's default port
file - The "file" portion of the URL.
ph - The protocol handler to use with this URL.
Throws:
MalformedURLException - If no protocol handler can be loaded for the specified protocol.
SecurityException - If the SecurityManager exists and does not allow the caller to specify its own protocol handler.
Since:
1.2

URL

public URL(String protocol,
           String host,
           String file)
            throws MalformedURLException
Constructs a URL and loads a protocol handler for the values passed in as arugments. Uses the default port for the protocol.
Parameters:
protocol - The protocol for this URL ("http", "ftp", etc)
host - The hostname or IP address for this URL
file - The "file" portion of this URL.
Throws:
MalformedURLException - If a protocol handler cannot be loaded or a parse error occurs.

URL

public URL(URL context,
           String spec)
            throws MalformedURLException
This method parses a String representation of a URL within the context of an existing URL. Principally this means that any fields not present the URL are inheritied from the context URL. This allows relative URL's to be easily constructed. If the context argument is null, then a complete URL must be specified in the URL string. If the protocol parsed out of the URL is different from the context URL's protocol, then then URL String is also expected to be a complete URL.
Parameters:
context - The context on which to parse the specification
spec - The string to parse an URL
Throws:
MalformedURLException - If a protocol handler cannot be found for the URL cannot be parsed

URL

public URL(URL context,
           String spec,
           URLStreamHandler ph)
            throws MalformedURLException
Creates an URL from given arguments This method parses a String representation of a URL within the context of an existing URL. Principally this means that any fields not present the URL are inheritied from the context URL. This allows relative URL's to be easily constructed. If the context argument is null, then a complete URL must be specified in the URL string. If the protocol parsed out of the URL is different from the context URL's protocol, then then URL String is also expected to be a complete URL.

Additionally, this method allows the caller to specify a protocol handler to use instead of the default. If this handler is specified, the caller must have the "specifyStreamHandler" permission (see NetPermission) or a SecurityException will be thrown.

Parameters:
context - The context in which to parse the specification
spec - The string to parse as an URL
ph - The stream handler for the URL
Throws:
MalformedURLException - If a protocol handler cannot be found or the URL cannot be parsed
SecurityException - If the SecurityManager exists and does not allow the caller to specify its own protocol handler.
Since:
1.2

Method Details

equals

public boolean equals(Object obj)
Test another URL for equality with this one. This will be true only if the argument is non-null and all of the fields in the URL's match exactly (ie, protocol, host, port, file, and ref). Overrides Object.equals(), implemented by calling the equals method of the handler.
Overrides:
equals in interface Object
Parameters:
obj - The URL to compare with
Returns:
true if the URL is equal, false otherwise

getAuthority

public String getAuthority()
Returns the authority of the URL
Returns:
The authority specified in this URL.
Since:
1.3

getContent

public Object getContent()
            throws IOException
Returns the contents of this URL as an object by first opening a connection, then calling the getContent() method against the connection
Returns:
A content object for this URL
Throws:
IOException - If opening the connection or getting the content fails.
Since:
1.3

getContent

public Object getContent(Class<T>[] classes)
            throws IOException
Gets the contents of this URL
Parameters:
classes - The allow classes for the content object.
Returns:
a context object for this URL.
Throws:
IOException - If an error occurs

getDefaultPort

public int getDefaultPort()
Returns the default port of the URL. If the StreamHandler for the URL protocol does not define a default port it returns -1.
Returns:
The default port of the current protocol.

getFile

public String getFile()
Returns the file portion of the URL. Defined as path[?query]. Returns the empty string if there is no file portion.
Returns:
The filename specified in this URL, or an empty string if empty.

getHost

public String getHost()
Returns the host of the URL
Returns:
The host specified in this URL.

getPath

public String getPath()
Returns the path of the URL. This is the part of the file before any '?' character.
Returns:
The path specified in this URL, or null if empty.
Since:
1.3

getPort

public int getPort()
Returns the port number of this URL or -1 if the default port number is being used.
Returns:
The port number

getProtocol

public String getProtocol()
Returns the protocol of the URL
Returns:
The specified protocol.

getQuery

public String getQuery()
Returns the query of the URL. This is the part of the file before the '?'.
Returns:
the query part of the file, or null when there is no query part.

getRef

public String getRef()
Returns the ref (sometimes called the "# reference" or "anchor") portion of the URL.
Returns:
The ref

getUserInfo

public String getUserInfo()
Returns the user information of the URL. This is the part of the host name before the '@'.
Returns:
the user at a particular host or null when no user defined.

hashCode

public int hashCode()
Returns a hashcode computed by the URLStreamHandler of this URL
Overrides:
hashCode in interface Object
Returns:
The hashcode for this URL.

openConnection

public URLConnection openConnection()
            throws IOException
Returns a URLConnection object that represents a connection to the remote object referred to by the URL. The URLConnection is created by calling the openConnection() method of the protocol handler
Returns:
A URLConnection for this URL
Throws:
IOException - If an error occurs

openStream

public InputStream openStream()
            throws IOException
Opens a connection to this URL and returns an InputStream for reading from that connection
Returns:
An InputStream for this URL.
Throws:
IOException - If an error occurs

sameFile

public boolean sameFile(URL url)
Tests whether or not another URL refers to the same "file" as this one. This will be true if and only if the passed object is not null, is a URL, and matches all fields but the ref (ie, protocol, host, port, and file);
Parameters:
url - The URL object to test with
Returns:
true if URL matches this URL's file, false otherwise

set

protected void set(String protocol,
                   String host,
                   int port,
                   String file,
                   String ref)
Sets the specified fields of the URL. This is not a public method so that only URLStreamHandlers can modify URL fields. This might be called by the parseURL() method in that class. URLs are otherwise constant. If the given protocol does not exist, it will keep the previously set protocol.
Parameters:
protocol - The protocol name for this URL
host - The hostname or IP address for this URL
port - The port number of this URL
file - The "file" portion of this URL.
ref - The anchor portion of this URL.

set

protected void set(String protocol,
                   String host,
                   int port,
                   String authority,
                   String userInfo,
                   String path,
                   String query,
                   String ref)
Sets the specified fields of the URL. This is not a public method so that only URLStreamHandlers can modify URL fields. URLs are otherwise constant. If the given protocol does not exist, it will keep the previously set protocol.
Parameters:
protocol - The protocol name for this URL.
host - The hostname or IP address for this URL.
port - The port number of this URL.
authority - The authority of this URL.
userInfo - The user and password (if needed) of this URL.
path - The "path" portion of this URL.
query - The query of this URL.
ref - The anchor portion of this URL.
Since:
1.3

setURLStreamHandlerFactory

public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac)
Sets the URLStreamHandlerFactory for this class. This factory is responsible for returning the appropriate protocol handler for a given URL.
Parameters:
fac - The URLStreamHandlerFactory class to use
Throws:
SecurityException - If a security manager exists and its checkSetFactory method doesn't allow the operation

toExternalForm

public String toExternalForm()
Returns a String representing this URL. The String returned is created by calling the protocol handler's toExternalForm() method.
Returns:
A string for this URL

toString

public String toString()
Returns a String representing this URL. Identical to toExternalForm(). The value returned is created by the protocol handler's toExternalForm method. Overrides Object.toString()
Overrides:
toString in interface Object
Returns:
A string for this URL

toURI

public URI toURI()
            throws URISyntaxException
Returns the equivalent URI object for this URL. This is the same as calling new URI(this.toString()). RFC2396-compliant URLs are guaranteed a successful conversion to a URI instance. However, there are some values which form valid URLs, but which do not also form RFC2396-compliant URIs.
Throws:
URISyntaxException - if this URL is not RFC2396-compliant, and thus can not be successfully converted to a URI.

URL.java -- Uniform Resource Locator Class Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.