URL
In this chapter you will learn:
What is URL
A URL is a unique address to an Internet resource.
Here is a URL: http://www.java2s.com:80/index.htm
.
HTTP
is the protocol to use to retrieve the resource.http://www.yahoo.com/
is the host, where the resource resides.80
is the port number./index.htm
specifies the path of the URL.
In Java, a URL is represented by a java.net.URL
object. And it has
the following constructors.
URL(String urlSpecifier) throws MalformedURLException
create URL from stringURL(String protocolName, String hostName, int port, String path) throws MalformedURLException
break up the URL into its component partsURL(String protocolName, String hostName, String path) throws MalformedURLException
break up the URL into its component partsURL(URL urlObj, String urlSpecifier) throws MalformedURLException
use an existing URL as a reference context and then create a new URL from that context.
The following code creates a URL from a string. The domain name in www.java2s.com. The protocol is http.
URL myUrl = new URL ("http://www.java2s.com/");
Because no page is specified, the default page is assumed. The following lines of code create identical URL objects.
URL j1 = new URL ("http://www.java2s.com/index.html");
URL j2 = new URL ("http://www.java2s.com", "/index.html");
URL j3 = new URL ("http://www.java2s.com", 80, "/index.html");
Get URLConnection
To access the actual content, create a URLConnection
object
from it, using its openConnection()
method, like this:
openConnection()
has the following general form:
URLConnection openConnection( ) throws IOException
It returns a URLConnection object associated with the invoking URL object.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » URL URI