Java Reference
In-Depth Information
When the code is executed, it retrieves the data and prints it to the standard output stream as
shown in the next screenshot:
How it works...
The
HttpRequest
object automatically handles all the network steps necessary to create a
connection between your application and a remote web server. Here is what is going on in the
code snippet:
1.
The URL
—the first item is the declaration of the URL location. The code sets up the
variable
url
as the location of the Wikipedia entry that we want to retrieve.
2.
Connecting to the server
—next, we declare an instance of
HttpRequest
to handle
the connectivity and manage the data. The
location:String
property of the
HttpRequest
instance is assigned the variable
url
. The other interesting property
is the
HttpRequest.method
property, which specifies the HTTP method to use
when interacting with the server. For the recipe's code, we set the HTTP method to
HttpRequest.GET
(see
There's more,
next).
3.
Handling the response
—inally, we define event-handler functions for the
HttpRequest
instance. These event handlers will get invoked at different
phases of the request/response life cycle. In the code snippet, we are only
showing the
onInput
event-handler function in detail. This function is invoked
when all the bytes for the requested resource are received from the server. In the
code, the function basically loops through the received bytes from the IO stream
and prints the data, as shown in the previous screenshot.