Java Reference
In-Depth Information
Getting ready
Prior to getting started with
HttpRequest
, you should have an understanding of the basic
mechanics behind the Web and its HTTP protocol (see the HTTP reference at the end of
this recipe). JavaFX's
HttpRequest
class, located in the
javafx.io.http
package,
provides ways to manage communication between your JavaFX client application and a
remote web server. To illustrate the use of the
HttpRequest
class, we will use it to pull
down information from Wikipedia's entry about JavaFX programming language at the URL
http://en.wikipedia.org/wiki/JavaFX
. In future recipes, you will see how to use
HttpRequest
in conjunction with other data-specific APIs such as RSS. It is also a definite
plus to be familiar with Java's IO API when working with the HttpRequest API.
How to do it...
The code snippet in this recipe shows you how to use the
HttpRequest
object to send
a request to a server and handle the response using event-handler functions. The code
segment given next show an abbreviated version of the code. Refer to
ch06/source-code/
src/http/HttpRequestGET.fx
for a complete listing of the code.
var
url
= "http://en.wikipedia.org/wiki/JavaFX";
var http = HttpRequest {
location:
url
method:
HttpRequest.GET
...
onInput: function
(in: java.io.InputStream) {
if(in.available() > 0){
println ("Printing result from {url}");
var reader:BufferedReader;
try{
reader = new BufferedReader(
new InputStreamReader(in));
var line;
while((line = reader.readLine()) != null){
println(line)
}
}finally{
reader.close();
in.close();
}
}
}
...
}
http.start();




