/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.net; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Hashtable; import java.util.jar.JarFile; import libcore.net.url.FileHandler; import libcore.net.url.FtpHandler; import libcore.net.url.JarHandler; import libcore.net.url.UrlUtils; /** * A Uniform Resource Locator that identifies the location of an Internet * resource as specified by RFC * 1738. * *
Component | Example value | Also known as |
---|---|---|
{@link #getProtocol() Protocol} | {@code http} | scheme |
{@link #getAuthority() Authority} | {@code username:password@host:8080} | |
{@link #getUserInfo() User Info} | {@code username:password} | |
{@link #getHost() Host} | {@code host} | |
{@link #getPort() Port} | {@code 8080} | |
{@link #getFile() File} | {@code /directory/file?query} | |
{@link #getPath() Path} | {@code /directory/file} | |
{@link #getQuery() Query} | {@code query} | |
{@link #getRef() Ref} | {@code ref} | fragment |
The {@link URI} class can be used to manipulate URLs of any protocol.
*/
public final class URL implements Serializable {
private static final long serialVersionUID = -7627629688361524110L;
private static URLStreamHandlerFactory streamHandlerFactory;
/** Cache of protocols to their handlers */
private static final Hashtable Some implementations of URL.equals() resolve host names over the
* network. This is problematic:
* This problem is fixed in Android 4.0 (Ice Cream Sandwich). In that
* release, URLs are only equal if their host names are equal (ignoring
* case).
*/
@Override public boolean equals(Object o) {
if (o == null) {
return false;
}
if (this == o) {
return true;
}
if (this.getClass() != o.getClass()) {
return false;
}
return streamHandler.equals(this, (URL) o);
}
/**
* Returns true if this URL refers to the same resource as {@code otherURL}.
* All URL components except the reference field are compared.
*/
public boolean sameFile(URL otherURL) {
return streamHandler.sameFile(this, otherURL);
}
@Override public int hashCode() {
if (hashCode == 0) {
hashCode = streamHandler.hashCode(this);
}
return hashCode;
}
/**
* Sets the receiver's stream handler to one which is appropriate for its
* protocol.
*
* Note that this will overwrite any existing stream handler with the new
* one. Senders must check if the streamHandler is null before calling the
* method if they do not want this behavior (a speed optimization).
*
* @throws MalformedURLException if no reasonable handler is available.
*/
void setupStreamHandler() {
// Check for a cached (previously looked up) handler for
// the requested protocol.
streamHandler = streamHandlers.get(protocol);
if (streamHandler != null) {
return;
}
// If there is a stream handler factory, then attempt to
// use it to create the handler.
if (streamHandlerFactory != null) {
streamHandler = streamHandlerFactory.createURLStreamHandler(protocol);
if (streamHandler != null) {
streamHandlers.put(protocol, streamHandler);
return;
}
}
// Check if there is a list of packages which can provide handlers.
// If so, then walk this list looking for an applicable one.
String packageList = System.getProperty("java.protocol.handler.pkgs");
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (packageList != null && contextClassLoader != null) {
for (String packageName : packageList.split("\\|")) {
String className = packageName + "." + protocol + ".Handler";
try {
Class> c = contextClassLoader.loadClass(className);
streamHandler = (URLStreamHandler) c.newInstance();
if (streamHandler != null) {
streamHandlers.put(protocol, streamHandler);
}
return;
} catch (IllegalAccessException ignored) {
} catch (InstantiationException ignored) {
} catch (ClassNotFoundException ignored) {
}
}
}
// Fall back to a built-in stream handler if the user didn't supply one
if (protocol.equals("file")) {
streamHandler = new FileHandler();
} else if (protocol.equals("ftp")) {
streamHandler = new FtpHandler();
} else if (protocol.equals("http")) {
try {
String name = "com.android.okhttp.HttpHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
} else if (protocol.equals("https")) {
try {
String name = "com.android.okhttp.HttpsHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
} else if (protocol.equals("jar")) {
streamHandler = new JarHandler();
}
if (streamHandler != null) {
streamHandlers.put(protocol, streamHandler);
}
}
/**
* Returns the content of the resource which is referred by this URL. By
* default this returns an {@code InputStream}, or null if the content type
* of the response is unknown.
*/
public final Object getContent() throws IOException {
return openConnection().getContent();
}
/**
* Equivalent to {@code openConnection().getContent(types)}.
*/
@SuppressWarnings("unchecked") // Param not generic in spec
public final Object getContent(Class[] types) throws IOException {
return openConnection().getContent(types);
}
/**
* Equivalent to {@code openConnection().getInputStream(types)}.
*/
public final InputStream openStream() throws IOException {
return openConnection().getInputStream();
}
/**
* Returns a new connection to the resource referred to by this URL.
*
* @throws IOException if an error occurs while opening the connection.
*/
public URLConnection openConnection() throws IOException {
return streamHandler.openConnection(this);
}
/**
* Returns a new connection to the resource referred to by this URL.
*
* @param proxy the proxy through which the connection will be established.
* @throws IOException if an I/O error occurs while opening the connection.
* @throws IllegalArgumentException if the argument proxy is null or of is
* an invalid type.
* @throws UnsupportedOperationException if the protocol handler does not
* support opening connections through proxies.
*/
public URLConnection openConnection(Proxy proxy) throws IOException {
if (proxy == null) {
throw new IllegalArgumentException("proxy == null");
}
return streamHandler.openConnection(this, proxy);
}
/**
* Returns the URI equivalent to this URL.
*
* @throws URISyntaxException if this URL cannot be converted into a URI.
*/
public URI toURI() throws URISyntaxException {
return new URI(toExternalForm());
}
/**
* Encodes this URL to the equivalent URI after escaping characters that are
* not permitted by URI.
*
* @hide
*/
public URI toURILenient() throws URISyntaxException {
if (streamHandler == null) {
throw new IllegalStateException(protocol);
}
return new URI(streamHandler.toExternalForm(this, true));
}
/**
* Returns a string containing a concise, human-readable representation of
* this URL. The returned string is the same as the result of the method
* {@code toExternalForm()}.
*/
@Override public String toString() {
return toExternalForm();
}
/**
* Returns a string containing a concise, human-readable representation of
* this URL.
*/
public String toExternalForm() {
if (streamHandler == null) {
return "unknown protocol(" + protocol + ")://" + host + file;
}
return streamHandler.toExternalForm(this);
}
private void readObject(ObjectInputStream stream) throws IOException {
try {
stream.defaultReadObject();
if (host != null && authority == null) {
fixURL(true);
} else if (authority != null) {
int index;
if ((index = authority.lastIndexOf('@')) > -1) {
userInfo = authority.substring(0, index);
}
if (file != null && (index = file.indexOf('?')) > -1) {
query = file.substring(index + 1);
path = file.substring(0, index);
} else {
path = file;
}
}
setupStreamHandler();
if (streamHandler == null) {
throw new IOException("Unknown protocol: " + protocol);
}
hashCode = 0; // necessary until http://b/4471249 is fixed
} catch (ClassNotFoundException e) {
throw new IOException(e);
}
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
}
/** @hide */
public int getEffectivePort() {
return URI.getEffectivePort(protocol, port);
}
/**
* Returns the protocol of this URL like "http" or "file". This is also
* known as the scheme. The returned string is lower case.
*/
public String getProtocol() {
return protocol;
}
/**
* Returns the authority part of this URL, or null if this URL has no
* authority.
*/
public String getAuthority() {
return authority;
}
/**
* Returns the user info of this URL, or null if this URL has no user info.
*/
public String getUserInfo() {
return userInfo;
}
/**
* Returns the host name or IP address of this URL.
*/
public String getHost() {
return host;
}
/**
* Returns the port number of this URL or {@code -1} if this URL has no
* explicit port.
*
* If this URL has no explicit port, connections opened using this URL
* will use its {@link #getDefaultPort() default port}.
*/
public int getPort() {
return port;
}
/**
* Returns the default port number of the protocol used by this URL. If no
* default port is defined by the protocol or the {@code URLStreamHandler},
* {@code -1} will be returned.
*
* @see URLStreamHandler#getDefaultPort
*/
public int getDefaultPort() {
return streamHandler.getDefaultPort();
}
/**
* Returns the file of this URL.
*/
public String getFile() {
return file;
}
/**
* Returns the path part of this URL.
*/
public String getPath() {
return path;
}
/**
* Returns the query part of this URL, or null if this URL has no query.
*/
public String getQuery() {
return query;
}
/**
* Returns the value of the reference part of this URL, or null if this URL
* has no reference part. This is also known as the fragment.
*/
public String getRef() {
return ref;
}
/**
* Sets the properties of this URL using the provided arguments. Only a
* {@code URLStreamHandler} can use this method to set fields of the
* existing URL instance. A URL is generally constant.
*/
protected void set(String protocol, String host, int port, String authority, String userInfo,
String path, String query, String ref) {
String file = path;
if (query != null && !query.isEmpty()) {
file += "?" + query;
}
set(protocol, host, port, file, ref);
this.authority = authority;
this.userInfo = userInfo;
this.path = path;
this.query = query;
}
}
Network I/O Warning
*
*
*