| Table of Contents

# Working with URLs

> URL is an acronym that stands for Uniform Resource Locator and is a reference (an address) to a resource on the Internet. URLs are the doorway to the Internet and the World Wide Web. You provide URLs to your favorite Web browser so that it can locate files on the Internet in the same way as you provide addresses on letters so that the post office can locate your correspondents.

> The Java programs you write that interact with the Internet may also use URLs to find the resources on the Internet they wish to access. The java.net package contains a class called URL that your Java programs can use to represent a URL address.

> Note about terminology: The term URL can be ambiguous--does it mean the concept of an address to something on the Internet or does it refer to a URL object in your Java program? Usually, the meaning is clear from the context of the sentence, or it doesn't matter because the statement applies to both. However, where the meaning of URL needs to be specifically one or the other, this text uses URL address to mean the concept of an Internet address and URL object to refer to an instance of the URL class in your program.

> #### What Is a URL?

> > A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource.

> #### Creating a URL

> > Within your Java programs, you can create a URL object that represents a URL address. The URL object always refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL components.

> #### Parsing a URL

> > Gone are the days of parsing a URL to find out the host name, filename, and other information. With a valid URL object you can call any of its accessor methods to get all of that information from the URL without doing any string parsing!

> #### Reading Directly from a URL

> > This section shows how your Java programs can read from a URL using the `openStream()` method.

> #### Connecting to a URL

> > If you want to do more than just read from a URL, you can connect to it by calling `openConnection()` on the URL. The `openConnection()` method returns a URLConnection object that you can use for more general communications with the URL, such as reading from it, writing to it, or querying it for content and other information.

> #### Reading from and Writing to a URLConnection

> > Some URLs, such as many that are connected to cgi-bin scripts, allow you to (or even require you to) write information to the URL. For example, a search script may require detailed query data to be written to the URL before the search can be performed. This section shows you how to write to a URL and how to get results back.

| Table of Contents