Spec-Zone .ru
спецификации, руководства, описания, API

JavaFX: Bringing Rich Experiences To All the Screens Of Your Life

Profile: desktop, common

Overview

An API to make asynchronous HTTP requests. Can also be to invoke RESTful Web Services.

HttpRequest allows one to specify a location and method and start a HTTP operation with the function enqueue(). Various variables such as started, connecting, writing, reading and done will change state as the operation progresses. For operations that transfer large amounts of data, the percentage progress can be computed using the read, toread, written and towrite variables. Callback funcitons are also called to indicate changes in state as the operation progresses.

Performing a GET request

The example snippet below performs a HTTP GET request and prints changes in state to the console.

def request = HttpRequest {

    location: "http://javafx.com";

    onStarted: function() { println("started") }
    onConnecting: function() { println("connecting...") }
    onDoneConnect: function() { println("doneConnect") }
    onReadingHeaders: function() { println("readingHeaders...") }
    onResponseCode: function(code:Integer) { println("responseCode: {code}") }
    onResponseMessage: function(msg:String) { println("responseMessage: {msg}") }

    onResponseHeaders: function(headerNames: String[]) {
        println("there are {headerNames.size()} response headers:");
        for (name in headerNames) {
            println("    {name}: {request.getResponseHeaderValue(name)}");
        }
    }

    onToRead: function(bytes: Integer) { println("bytes to read: {bytes}") }

    // The onRead callback is called when some more data has been read into
    // the input stream's buffer.  The input stream will not be available until
    // the onInput call back is called, but onRead can be used to show the 
    // progress of reading the content from the location.
    onRead: function(bytes: Integer) {
        def progress = if (request.toread > 0) "({(bytes * 100 / request.toread)}%)" else "";
        println("bytes read: {bytes} {progress}");
    }

    // The content of a response can be accessed in the onInput callback function.
    // Be sure to close the input sream when finished with it in order to allow
    // the HttpRequest implementation to clean up resources related to this
    // request as promptly as possible.
    onInput: function(is: java.io.InputStream) {
        // use input stream to access content here. 
        // can use input.available() to see how many bytes are available.
        try {
            println("bytes of content available: {is.available()}");
        } finally {
            is.close();
        }
    }

    onException: function(ex: Exception) { println("exception: {ex.printStackTrace()}") }
    onDoneRead: function() { println("doneRead") }
    onDone: function() { println("done") }
}
request.enqueue();

The above snippet would print on the console -

started
connecting...
doneConnect
readingHeaders...
responseCode: 200
responseMessage: OK
there are 7 response headers:
    x-powered-by: Servlet/2.5
    server: Sun Java System Application Server 9.1_01
    etag: W/"14890-1218585423000"
    last-modified: Tue, 12 Aug 2008 23:57:03 GMT
    content-type: text/html
    content-length: 14890
    date: Tue, 28 Oct 2008 04:42:32 GMT
bytes to read: 14890
bytes read: 4061 (27%)
bytes read: 5501 (36%)
bytes read: 6941 (46%)
bytes read: 8381 (56%)
bytes read: 9821 (65%)
bytes read: 11261 (75%)
bytes read: 12701 (85%)
bytes read: 14890 (100%)
bytes of content available: 14890
doneRead
done

If the user enters a puposefully unknown host in the URL, such as: http://www.sun.comunknown.host/, the resulting output will look like this:

started
connecting...
exception: java.net.UnknownHostException: www.sun.comunknown.host
done

Life cycle

Progress of the HttpRequest operation life cycle is tracked by changes in variable values and associated callback variables, if specified.

Sequence of changes to variable values for a HTTP GET request operation.

variable name initial or previous value new value description
1 started false true Indicates that the HTTP request has started execution.
2 connecting false true Indicates that the HTTP request will now attempt to connect to location.
3 doneConnect false true HTTP connection to location has been opened successfully.
4 readingHeaders false true Indicates that the HTTP request will now attempt to read HTTP response headers from location.
5 responseCode 0 HTTP Response code (Integer) The HTTP response code has been read.
6 responseMessage null HTTP Response message (String) The HTTP response message has been read.
[6.a] error null error stream (InputStream) An error response is available (only if provided in HTTP response).
7 doneHeaders false true HTTP response headers have been read.
8 reading false true About to start reading the HTTP response body.
[8.a] toread 0 bytes to read (Integer) toread bytes of content available to be read.
[8.b] read 0 bytes read (Integer) read bytes of content that has just been read.
9 input null response body (InputStream) An InputStream providing access to the HTTP response body.
10 doneRead false true The entire HTTP response body has been read.
11 done false true The HTTP operation has finished.

Sequence of changes to variable values for a HTTP POST or PUT request operation.

variable name initial or old value new value description
1 started false true Indicates that the HTTP request has started execution.
2 connecting false true Indicates that the HTTP connection to location has started.
3 doneConnect false true HTTP connection to location has been opened successfully.
4 writing false true The writing of request content is about to start.
5 output null an OutputStream Output stream availalbe for writing request content. Writing of content to the HTTP connection will only happen after OutputStream.close() is called.
[5.a] towrite 0 bytes to write (Integer) towrite bytes of content is about to be written to location.
[5.b] written 0 bytes written (Integer) written bytes of content has just been written.
6 doneWrite false true The entire HTTP request body has been written
7 readingHeaders false true Indicates that the HTTP request will now attempt to read HTTP response headers from location.
8 responseCode 0 HTTP Response code (Integer) The HTTP response code has been read.
9 responseMessage null HTTP Response message (String) The HTTP response message has been read.
[9.a] error null error stream (InputStream) An error response is available (only if provided in HTTP response).
10 doneHeaders false true HTTP response headers have been read.
11 reading false true About to start reading the HTTP response body.
[11.a] toread 0 bytes to read (Integer) toread bytes of content available to be read.
[11.b] read 0 bytes read (Integer) read bytes of content that has just been read.
12 input null response body (InputStream) An InputStream providing access to the HTTP response body.
13 doneRead false true The entire HTTP response body has been read.
14 done false true The HTTP operation has finished.

Sequence of changes to variable values for a HTTP DELETE request operation.

variable name initial or previous value new value description
1 started false true Indicates that the HTTP request has started execution.
2 connecting false true Indicates that the HTTP connection to location has started.
3 doneConnect false true HTTP connection to location has been opened successfully.
4 readingHeaders false true Indicates that the HTTP request will now attempt to read HTTP response headers from location.
5 responseCode 0 HTTP Response code (Integer) The HTTP response code has been read.
6 responseMessage null HTTP Response message (String) The HTTP response message has been read.
[6.a] error null error stream (InputStream) An error response is available (only if provided in HTTP response).
7 doneHeaders false true HTTP response headers have been read.
8 done false true The HTTP operation has finished.

Error Handling

At any time after calling enqueue(), the exception variable can be assigned an exception. This indicates that there has been an error in the processing of the HttpRequest's operation. Subsequently, the done variable will be assigned the value true, indicating the end of execution of the HttpRequest's operation. In all cases after enqueue() has been called, the last event to happen will be the assignment of true to the done variable.

Canceling a HTTP operation

A request's HTTP operation can be cancelled by calling cancel() at any time after enqueue() has been called. This removes the request from the queue if it is queued, or interrupts the request if it has started executing. Both of these cases will cause the done variable to change value to true.

Profile: common

Variable Summary

accessnametypeCan ReadCan InitCan WriteDefault Valuedescription
public-readconnectingBoolean

Indicates that the request is attempting to connect to location.

publiccontextObject

Context object provided by appliction.

Context object provided by appliction. To be provided by and used by the application during asynchronus events as this request progresses. If context is assigned another HttPRequest object, it can be accessed from a trigger for the done variable to "chain" HTTP operations. Once this HttpRequest's operation is done, the one contained in context can be #enqueue()ed.

See Also:
enqueue(), done

 
publicDELETEString

HTTP DELETE method value.

HTTP DELETE method value. Can be assigned to method

 
public-readdoneBoolean

Indicates if this request's HTTP operation is finished.

public-readdoneConnectBoolean

Indicates that the HTTP connection to location has been opened successfully.

public-readdoneHeadersBoolean

Indicates that the HTTP headers have successfully been read from location.

Indicates that the HTTP headers have successfully been read from location. These HTTP headers are availalbe via getResponseHeaderNames() and getResponseHeaderValue(String) if the value is true.

See Also:
onDoneHeaders

 
public-readdoneReadBoolean

Indicates if reading of response content from location has finished.

Indicates if reading of response content from location has finished. The content has been stored in input if the value is true.

 
public-readdoneWriteBoolean

Indicates that the contents of output have been successfully written to location.

public-readerrorInputStream

Contains the error content for this request.

Contains the error content for this request. This variable gets assigned an input stream only if error content has been received from location.

 
public-readexceptionException

Contains an exception indicating an error occured with this request.

Contains an exception indicating an error occured with this request. This variable gets assigned an excception only if an exception is encountered during communication with location for this request. If this variable gets assigned an exception, the done variable will subsequently get assigned the value true.

 
publicGETString

HTTP GET method value.

HTTP GET method value. Can be assigned to method

 
public-readidInteger

Unique HTTP operation identifier for this request.

Unique HTTP operation identifier for this request. Assigned only as a result of calling the enqueue() function.

 
public-readinputInputStream

Contains the response content for this request.

Contains the response content for this request. This variable gets assigned an input stream only after the entire content of the request has been received from location.

 
publiclocationString

Target location for this HttpRequest.

Target location for this HttpRequest. URL format.

 
publicmethodString

Method to use for this request.

Method to use for this request. One of GET, POST, PUT, DELETE

 
publiconConnectingfunction():Void

Callback that is invoked once to indicate that the request is attempting to connect to location.

publiconDonefunction():Void

Callback that is invoked once to indicate that the request has finished execution.

publiconDoneConnectfunction():Void

Callback that is invoked once to indicate that the request is now connected to location.

publiconDoneHeadersfunction():Void

Callback that is invoked once to indicate that the request is done reading response headers.

Callback that is invoked once to indicate that the request is done reading response headers. responseCode, responseMessage and error, if sent, are also available at this time.

 
publiconDoneReadfunction():Void

Callback that is invoked once to indicate that the request is done reading the response body.

publiconDoneWritefunction():Void

Callback that is invoked once to indicate that the request is done writing and all of the data in output has been sent to location.

publiconErrorfunction(:InputStream):Void

Callback that is invoked once to indicate that an InputStream containing an error response from the server is now available.

Callback that is invoked once to indicate that an InputStream containing an error response from the server is now available. The provided InputStream must be closed when done reading in a finally block -

 try {
     // read from input
 } finally {
     input.close();
 }
 

 
publiconExceptionfunction(:Exception):Void

Callback that is invoked once to provide an application with an exception that occurred, if any, during the execution of this request.

publiconInputfunction(:InputStream):Void

Callback that is invoked once to indicate that the request body is now available.

Callback that is invoked once to indicate that the request body is now available. The provided InputStream must be closed when done reading in a finally block -

 try {
     // read from input, hand-off to a parser, etc
 } finally {
     input.close();
 }
 

 
publiconOutputfunction(:OutputStream):Void

Callback that is invoked once to provide an application with an opportunity to write data that is to be sent to location.

Callback that is invoked once to provide an application with an opportunity to write data that is to be sent to location. Valid for POST and PUT. To keep the application from blocking, the data is first accumulated in memory and sent after an application closes the OutputStream provided. The provided OutputStream must be closed to initiate the transfer, so wrapping the writes in a finally block is recommended -

 try {
     // write to output
 } finally {
     output.close();
 }
 

 
publiconReadfunction(:int):Void

Callback that is invoked to indicate the number of bytes read so far.

publiconReadingfunction():Void

Callback that is invoked once to indicate that the request is starting to read the response body.

publiconReadingHeadersfunction():Void

Callback that is invoked once to indicate that the request is starting to read HTTP reponse headers, responseCode, responseMessage and error, if any.

publiconResponseCodefunction(:int):Void

Callback that is invoked once to indicate that the HTTP response code from the server is now available.

Callback that is invoked once to indicate that the HTTP response code from the server is now available. Some commonly used HTTP response codes are defined in HttpStatus and can be used to compare with.

 
publiconResponseHeadersfunction(:Sequence):Void

Callback that is invoked once to indicate that HTTP response headers from the server are now available.

Callback that is invoked once to indicate that HTTP response headers from the server are now available. Some commonly used HTTP headers are defined in HttpHeaders and can be used to compare with.

 
publiconResponseMessagefunction(:String):Void

Callback that is invoked once to indicate that the HTTP response message from the server is now available.

publiconStartedfunction():Void

Callback that is invoked once to indicate that the request has started execution.

publiconToReadfunction(:int):Void

Callback that is invoked once to indicate the total number of bytes to read, if available.

Callback that is invoked once to indicate the total number of bytes to read, if available. This is usually the value of the content-length HTTP header, if set by the server.

See Also:
toread

 
publiconToWritefunction(:int):Void

Callback that is invoked once to indicate the total number of bytes to write.

publiconWritingfunction():Void

Callback that is invoked once to indicate that the request has started writing the data previously written to output by the application to location.

publiconWrittenfunction(:int):Void

Callback that is invoked to indicate the number of bytes written so far.

public-readoutputOutputStream

Contains data to be written to location during HTTP operations where method contains POST or PUT.

publicPOSTString

HTTP POST method value.

HTTP POST method value. Can be assigned to method

 
publicPUTString

HTTP PUT method value.

HTTP PUT method value. Can be assigned to method

 
public-readreadInteger

Number bytes read from the location into input.

public-readreadingBoolean

Indicates if reading response content from location is about to start.

public-readreadingHeadersBoolean

Indicates that the reading of HTTP headers from location has started.

public-readresponseCodeInteger

The HTTP response code to the request method from location.

The HTTP response code to the request method from location. Usually included in responseMessage

 
public-readresponseMessageString

The HTTP response message to the request method from location.

The HTTP response message to the request method from location. Usually includes the text representation of the responseCode

 
public-readstartedBoolean

Indicates if this request's operation has started.

Indicates if this request's operation has started. The operation has started when it has been pulled from the queue (see enqueue()) and preparation for the connection to location has started. If the value is true, this request's HTTP operation has started execution.

See Also:
onStarted

 
public-readtoreadInteger

Number of bytes expected to be read from input.

Number of bytes expected to be read from input. The number of bytes available in input when input is first made available, if content-length is set.

See Also:
onToRead

 
public-readtowriteInteger

The number of bytes already in output that are going to be written to location.

public-readwritingBoolean

Indicates that the contents of output are about to be written to location.

public-readwrittenInteger

Number of bytes in output that have been written to location.

Inherited Variables

Function Summary

public cancel() : Void

Cancel this request's HTTP operation.

Cancel this request's HTTP operation. If the request is queued or executing, calling this function will subsequently cause cause the done variable to change value to true.

 
public enqueue() : Integer

Starts a HTTP operation.

Starts a HTTP operation. Enqueues this request so that it can be processed. See the overview for how the operation can progress.

Returns
Integer
a unique identifier for this request's HTTP operation.
 
public getResponseHeaderNames() : <any>[]

Get the names of HTTP headers set on the HTTP response.

Get the names of HTTP headers set on the HTTP response.

See Also:
doneHeaders

Returns
<any>[]
a sequence of names of HTTP headers set on the HTTP response. Will be an empty sequence if HTTP response headers are not available yet.
&nbsp;
public getResponseHeaderValue(name: java.lang.String) : java.lang.String

Retrieve the value of the specified HTTP header name.

Retrieve the value of the specified HTTP header name. Must be one of the names in the sequence returned from getResponseHeaderNames(). Returns null if the specifed HTTP header is not set on the HTTP response.

Parameters
name
the HTTP response header name whose value is to be retrieved
Returns
String
&nbsp;
public setHeader(name: java.lang.String, value: java.lang.String) : java.lang.Object

Set the specified header and value as HTTP header on the outgoing HTTP request.

Set the specified header and value as HTTP header on the outgoing HTTP request. Existing headers of the same name, if any, are overwritten. Some commonly-used header names and values are defined in HttpHeaders

Parameters
name
the HTTP header name
value
the HTTP header value
Returns
Object
&nbsp;
public shutdown() : Void

Shut down HttpRequest queue, only after any currently queued and executing operations have completed.

Shut down HttpRequest queue, only after any currently queued and executing operations have completed. No more requests will be accepted after a shutdown.

&nbsp;
public shutdownNow() : Void

Shut down HttpRequest queue immediately.

Shut down HttpRequest queue immediately. Interrupt any currently executing operations and do not accept any more requests.

&nbsp;

Inherited Functions