Java Reference
In-Depth Information
Of course, this means the only way to represent a “+” symbol itself in a URL is to use the
hexadecimal ASCII code “%2B”.
Now that you understand how to construct a URL, it is time to see how to use them. This
will be covered in the next section.
Reading from URLs
Java allows you to read data from URLs. This forms the basis of HTTP programming in
Java. In this chapter you will see how to construct simple requests from web sites. What is
meant by a simple request? A simple request is a request where you only request data from
a URL. It can get much more complex than that. As you progress through the topic you will
learn more complex HTTP programming topics such as:
• HTTPS
• Posting Data
• Cookies
• Authentication
• Content Types
For now, we will focus on simply getting data from a URL, and leave the more complex
operations for later. There are three basic steps that you will need to carry out to read data
from a URL. These steps are summarized as follows:
• Create a URL Object
• Open a Stream
• Read Data from the Stream
We will begin by examining the Java URL class.
The URL Class
Java provides a class to hold URLs. Even though a URL is actually a String , it is conve-
nient to have a class to handle the URL. The URL class offers several advantages over storing
URLs as strings. There are methods to:
• Determine if URL is valid
• Extract information, such as host or schema
• Open a connection to the URL
To create a URL object, simply pass the URL string to the constructor of the URL class,
as follows:
URL url = new URL("http://www.httprecipes.com");
Search WWH ::




Custom Search