URL

In this chapter you will learn:

  1. What is URL
  2. How to get a connection from URL

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 string
  • URL(String protocolName, String hostName, int port, String path) throws MalformedURLException
    break up the URL into its component parts
  • URL(String protocolName, String hostName, String path) throws MalformedURLException
    break up the URL into its component parts
  • URL(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:

  1. Creating a URL with a single string
  2. Creating a URL With components
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface