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 functions 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 getRequest: HttpRequest = HttpRequest {
location: "http://www.wikipedia.org";
onStarted: function() {
println("onStarted - started performing method: {postRequest.method} on location: {postRequest.location}");
}
onConnecting: function() { println("onConnecting") }
onDoneConnect: function() { println("onDoneConnect") }
onReadingHeaders: function() { println("onReadingHeaders") }
onResponseCode: function(code:Integer) { println("onResponseCode - responseCode: {code}") }
onResponseMessage: function(msg:String) { println("onResponseMessage - responseMessage: {msg}") }
onResponseHeaders: function(headerNames: String[]) {
println("onResponseHeaders - there are {headerNames.size()} response headers:");
for (name in headerNames) {
println(" {name}: {getRequest.getResponseHeaderValue(name)}");
}
}
onReading: function() { println("onReading") }
onToRead: function(bytes: Integer) {
if (bytes < 0) {
println("onToRead - Content length not specified by server; bytes: {bytes}");
} else {
println("onToRead - total number of content 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) {
// The toread variable is non negative only if the server provides the content length
def progress =
if (getRequest.toread > 0) "({(bytes * 100 / getRequest.toread)}%)" else "";
println("onRead - 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("onInput - bytes of content available: {is.available()}");
} finally {
is.close();
}
}
onException: function(ex: java.lang.Exception) {
println("onException - exception: {ex.getClass()} {ex.getMessage()}");
}
onDoneRead: function() { println("onDoneRead") }
onDone: function() { println("onDone") }
}
getRequest.enqueue();
The above snippet would print on the console -
onStarted - started performing method: GET on location: http://www.wikipedia.org
onConnecting
onDoneConnect
onReadingHeaders
onResponseCode - responseCode: 200
onResponseMessage - responseMessage: OK
onResponseHeaders - there are 12 response headers:
date: Wed, 17 Dec 2008 19:26:37 GMT
server: Apache
x-powered-by: PHP/5.2.4-2ubuntu5wm1
cache-control: s-maxage=3600, must-revalidate, max-age=0
last-modified: Thu, 11 Dec 2008 09:19:49 GMT
content-type: text/html; charset=utf-8
content-length: 51605
x-cache: HIT from sq17.wikimedia.org
x-cache-lookup: HIT from sq17.wikimedia.org:80
age: 2
via: 1.0 sq27.wikimedia.org:3128 (squid/2.6.STABLE21), 1.0 sq17.wikimedia.org:80 (squid/2.6.STABLE21)
connection: keep-alive
onReading
onToRead - total number of content bytes to read: 51605
onRead - bytes read: 2023 (3%)
onRead - bytes read: 4631 (8%)
onRead - bytes read: 5935 (11%)
onRead - bytes read: 7239 (14%)
onRead - bytes read: 9847 (19%)
onRead - bytes read: 12455 (24%)
onRead - bytes read: 15063 (29%)
onRead - bytes read: 18975 (36%)
onRead - bytes read: 22887 (44%)
onRead - bytes read: 24191 (46%)
onRead - bytes read: 26799 (51%)
onRead - bytes read: 28103 (54%)
onRead - bytes read: 32015 (62%)
onRead - bytes read: 35927 (69%)
onRead - bytes read: 37231 (72%)
onRead - bytes read: 41327 (80%)
onRead - bytes read: 42447 (82%)
onRead - bytes read: 46543 (90%)
onRead - bytes read: 47663 (92%)
onRead - bytes read: 50271 (97%)
onRead - bytes read: 51605 (100%)
onInput - bytes of content available: 51605
onDoneRead
onDone
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:
onStarted - started performing method: GET on location: http://www.sun.comunknown.host/
onConnecting
onException - exception: class java.net.UnknownHostException www.sun.comunknown.host
onDone
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 and callback function variable name | initial or previous variable value | new value | description | |
---|---|---|---|---|
1 | started, onStarted | false |
true |
Indicates that the HTTP request has started execution. |
2 | connecting, onConnecting | false |
true |
Indicates that the HTTP request will now attempt to connect to location . |
3 | doneConnect, onDoneConnect | false |
true |
HTTP connection to location has been opened successfully. |
4 | readingHeaders, onReadingHeaders | false |
true |
Indicates that the HTTP request will now attempt to read HTTP response headers from location . |
5 | responseCode, onResponseCode | 0 |
HTTP Response code (Integer) | The HTTP response code has been read. |
6 | responseMessage, onResponseMessage | null |
HTTP Response message (String) | The HTTP response message has been read. |
[6.a] | error, onError | null |
error stream (InputStream) | An error response is available (only if provided in HTTP response). |
7 | doneHeaders, onDoneHeaders | false |
true |
HTTP response headers have been read. |
8 | reading, onReading | false |
true |
About to start reading the HTTP response body. |
[8.a] | toread, onToRead | 0 |
bytes to read (Integer) | toread bytes of content available to be read. |
[8.b] | read, onRead | 0 |
bytes read (Integer) | read bytes of content that has just been read. (shows read progress) |
9 | input, onInput | null |
response body (InputStream) | An InputStream providing access to the HTTP response body. |
10 | doneRead, onDoneRead | false |
true |
The entire HTTP response body has been read. |
11 | done, onDone | false |
true |
The HTTP operation has finished. |
Peforming a POST request
The example snippet below performs a HTTP POST request and prints changes in state to the console. It posts some abitrary content to a fictitious Servlet (TestServlet) that runs on the local host.
def testContent: String = "test content";
def testContentSize: Integer = testContent.getBytes().length;
class PostRequest extends HttpRequest {
override public var method = HttpRequest.POST;
// override the enqueue function in order to make sure the Content-Type
// and Content-Length headers are provided
override function enqueue(): Integer {
setHeader("Content-Type", "somecontent/type");
setHeader("Content-Length", "{testContentSize}");
return super.enqueue();
}
}
def postRequest: HttpRequest = PostRequest {
location: "http://localhost:8080/TestServlet/";
onStarted: function() {
println("onStarted - started performing method: {postRequest.method} on location: {postRequest.location}");
}
onConnecting: function() { println("onConnecting") }
onDoneConnect: function() { println("onDoneConnect") }
onWriting: function() { println("onWriting") }
// The content of a PUT or POST can be specified in the onOutput callback function.
// Be sure to close the output sream when finished with it in order to allow
// the HttpRequest implementation to clean up resources related to this
// request as promptly as possible. The calling next callback (onToWrite) depends
// the output stream being closed.
onOutput: function(os: java.io.OutputStream) {
try {
println("onOutput - about to write {testContentSize} bytes to output stream");
os.write(testContent.getBytes());
} finally {
println("onOutput - about to close output stream.");
os.close();
}
}
onToWrite: function(bytes: Integer) { println("onToWrite - entire content to be written: {bytes} bytes") }
onWritten: function(bytes: Integer) { println("onWritten - {bytes} bytes has now been written") }
onDoneWrite: function() { println("doneWrite") }
onReadingHeaders: function() { println("onReadingHeaders") }
onResponseCode: function(code:Integer) { println("onResponseCode - responseCode: {code}") }
onResponseMessage: function(msg:String) { println("onResponseMessage - responseMessage: {msg}") }
onResponseHeaders: function(headerNames: String[]) {
println("onResponseHeaders - there are {headerNames.size()} response headers:");
for (name in headerNames) {
println(" {name}: {postRequest.getResponseHeaderValue(name)}");
}
}
onReading: function() { println("onReading") }
onToRead: function(bytes: Integer) {
if (bytes < 0) {
println("onToRead - Content length not specified by server; bytes: {bytes}");
} else {
println("onToRead - total number of content 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) {
// The toread variable is non negative only if the server provides the content length
def progress =
if (postRequest.toread > 0) "({(bytes * 100 / postRequest.toread)}%)" else "";
println("onRead - 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("onInput - bytes of content available: {is.available()}");
} finally {
is.close();
}
}
onException: function(ex: java.lang.Exception) {
println("onException - exception: {ex.getClass()} {ex.getMessage()}");
}
onDoneRead: function() { println("onDoneRead") }
onDone: function() { println("onDone") }
};
postRequest.enqueue();
The above snippet would print on the console -
onStarted - started performing method: POST on location: http://localhost:8080/TestServlet/
onConnecting
onDoneConnect
onWriting
onOutput() about to write 12 bytes to output stream
onOutput() about to close output stream.
onToWrite - entire content to be written: 12 bytes
onWritten - 12 bytes has now been written
doneWrite
onReadingHeaders
onResponseCode - responseCode: 200
onResponseMessage - responseMessage: OK
onResponseHeaders - there are 6 response headers:
x-powered-by: JSP/2.1
server: GlassFish/v3
set-cookie: JSESSIONID=c7356338c17a201e00f3acf90271; Path=/TestServlet
content-type: text/html;charset=UTF-8
content-length: 325
date: Mon, 15 Dec 2008 21:00:38 GMT
onReading
onToRead - total number of content bytes to read: 325
onRead - bytes read: 325 (100%)
onInput - bytes of content available: 325
onDoneRead
onDone
Sequence of changes to variable values for a HTTP POST or PUT request operation.
variable name and callback function variable name | initial or previous variable value | new value | description | |
---|---|---|---|---|
1 | started, onStarted | false |
true |
Indicates that the HTTP request has started execution. |
2 | connecting, onConnecting | false |
true |
Indicates that the HTTP connection to location has started. |
3 | doneConnect, onDoneConnect | false |
true |
HTTP connection to location has been opened successfully. |
4 | writing, onWriting | false |
true |
The writing of request content is about to start. |
[4.a] | output, onOutput | 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. |
[4.b] | towrite, onToWrite | 0 |
bytes to write (Integer) | towrite bytes of content is about to be written to location. This is the number of bytes contained in the output stream output at the time OutputStream.close() is called. |
[4.c] | written, onWritten | 0 |
bytes written (Integer) | written bytes of content has been written (shows write progress). |
[4.d] | doneWrite, onDoneWrite | false |
true |
The entire HTTP request body has been written |
5 | readingHeaders, onReadingHeaders | false |
true |
Indicates that the HTTP request will now attempt to read HTTP response headers from location . |
6 | responseCode, onResponseCode | 0 |
HTTP Response code (Integer) | The HTTP response code has been read. |
7 | responseMessage, onResponseMessage | null |
HTTP Response message (String) | The HTTP response message has been read. |
[7.a] | error, onError | null |
error stream (InputStream) | An error response is available (only if provided in HTTP response). |
8 | doneHeaders, onDoneHeaders | false |
true |
HTTP response headers have been read. |
9 | reading, onReading | false |
true |
About to start reading the HTTP response body. |
[9.a] | toread, onToRead | 0 |
bytes to read (Integer) | toread bytes of content available to be read. |
[9.b] | read, onRead | 0 |
bytes read (Integer) | read bytes of content that has just been read. (shows read progress) |
10 | input, onInput | null |
response body (InputStream) | An InputStream providing access to the HTTP response body. |
11 | doneRead, onDoneRead | false |
true |
The entire HTTP response body has been read. |
12 | done, onDone | false |
true |
The HTTP operation has finished. |
Sequence of changes to variable values for a HTTP DELETE request operation.
variable name and callback function variable name | initial or previous variable value | new value | description | |
---|---|---|---|---|
1 | started, onStarted | false |
true |
Indicates that the HTTP request has started execution. |
2 | connecting, onConnecting | false |
true |
Indicates that the HTTP connection to location has started. |
3 | doneConnect, onDoneConnect | false |
true |
HTTP connection to location has been opened successfully. |
4 | readingHeaders, onReadingHeaders | false |
true |
Indicates that the HTTP request will now attempt to read HTTP response headers from location . |
5 | responseCode, onResponseCode | 0 |
HTTP Response code (Integer) | The HTTP response code has been read. | 6 | responseMessage, onResponseMessage | null |
HTTP Response message (String) | The HTTP response message has been read. |
[6.a] | error, onError | null |
error stream (InputStream) | An error response is available (only if provided in HTTP response). |
7 | doneHeaders, onDoneHeaders | false |
true |
HTTP response headers have been read. |
8 | done, onDone | 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
access | name | type | Can Read | Can Init | Can Write | Default Value | description |
---|---|---|---|---|---|---|---|
public-read protected | connecting | Boolean | subclass | subclass |
Indicates that the request is attempting to connect to location. |
||
public | context | Object |
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 |
||||
public | DELETE | String |
HTTP DELETE method value. HTTP DELETE method value. Can be assigned to method |
||||
public-read protected | done | Boolean | subclass | subclass |
Indicates if this request's HTTP operation is finished. |
||
public-read protected | doneConnect | Boolean | subclass | subclass |
Indicates that the HTTP connection to location has been opened successfully. |
||
public-read protected | doneHeaders | Boolean | subclass | subclass |
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
See Also:
|
||
public-read protected | doneRead | Boolean | subclass | subclass |
Indicates if reading of response content from location has finished. |
||
public-read protected | doneWrite | Boolean | subclass | subclass |
Indicates that the contents of output have been successfully written to location. |
||
public-read protected | error | InputStream | subclass | subclass |
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-read protected | exception | Exception | subclass | subclass |
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 |
||
public | GET | String |
HTTP GET method value. HTTP GET method value. Can be assigned to method |
||||
public-read protected | id | Integer | subclass | subclass |
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-read protected | input | InputStream | subclass | subclass |
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. |
||
public | location | String |
Target location for this HttpRequest. Target location for this HttpRequest. URL format. |
||||
public | method | String |
Method to use for this request. |
||||
public | onConnecting | function():Void |
Callback that is invoked once to indicate that the request is attempting to connect to location. |
||||
public | onDone | function():Void |
Callback that is invoked once to indicate that the request has finished execution. |
||||
public | onDoneConnect | function():Void |
Callback that is invoked once to indicate that the request is now connected to location. |
||||
public | onDoneHeaders | function():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. |
||||
public | onDoneRead | function():Void |
Callback that is invoked once to indicate that the request is done reading the response body. |
||||
public | onDoneWrite | function():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. |
||||
public | onError | function(:InputStream):Void |
Callback that is invoked once to indicate that an
Callback that is invoked once to indicate that an
|
||||
public | onException | function(:Exception):Void |
Callback that is invoked once to provide an application with an exception that occurred, if any, during the execution of this request. |
||||
public | onInput | function(: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 |
||||
public | onOutput | function(: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
|
||||
public | onRead | function(:int):Void |
Callback that is invoked to indicate the number of bytes read so far. |
||||
public | onReading | function():Void |
Callback that is invoked once to indicate that the request is starting to read the response body. |
||||
public | onReadingHeaders | function():Void |
Callback that is invoked once to indicate that the request is starting to read HTTP reponse headers, responseCode, responseMessage and error, if any. |
||||
public | onResponseCode | function(: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. |
||||
public | onResponseHeaders | function(: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. |
||||
public | onResponseMessage | function(:String):Void |
Callback that is invoked once to indicate that the HTTP response message from the server is now available. |
||||
public | onStarted | function():Void |
Callback that is invoked once to indicate that the request has started execution. |
||||
public | onToRead | function(: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
See Also:
|
||||
public | onToWrite | function(:int):Void |
Callback that is invoked once to indicate the total number of bytes to write. |
||||
public | onWriting | function():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. |
||||
public | onWritten | function(:int):Void |
Callback that is invoked to indicate the number of bytes written so far. |
||||
public-read protected | output | OutputStream | subclass | subclass |
Contains data to be written to location during HTTP operations where method contains POST or PUT. |
||
public | POST | String |
HTTP POST method value. HTTP POST method value. Can be assigned to method |
||||
public | PUT | String |
HTTP PUT method value. HTTP PUT method value. Can be assigned to method |
||||
public-read protected | read | Integer | subclass | subclass |
Number bytes read from the location into input. |
||
public-read protected | reading | Boolean | subclass | subclass |
Indicates if reading response content from location is about to start. |
||
public-read protected | readingHeaders | Boolean | subclass | subclass |
Indicates that the reading of HTTP headers from location has started. |
||
public-read protected | responseCode | Integer | subclass | subclass |
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-read protected | responseMessage | String | subclass | subclass |
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-read protected | started | Boolean | subclass | subclass |
Indicates if this request's operation has started. |
||
public-read protected | toread | Integer | subclass | subclass |
Number of bytes expected to be read from input. |
||
public-read protected | towrite | Integer | subclass | subclass |
The number of bytes already in output that are going to be written to location. |
||
public-read protected | writing | Boolean | subclass | subclass |
Indicates that the contents of output are about to be written to location. |
||
public-read protected | written | Integer | subclass | subclass |
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
- 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.
- 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
- 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