TWebHttpRequest
The TWebHttpRequest
is a component to perform HTTP(s)
requests to a server. The HTTP
requests command can be:
httpCUSTOM : a custom HTTP command set with WebHttpRequest.CustomCommand
httpDELETE : a HTTP DELETE command
httpGET : a HTTP GET command (default)
httpHEAD : a HTTP HEAD command
httpPOST : a HTTP POST command
httpPUT : a HTTP PUT command
Optionally, HTTP request headers can be set. The HTTP request headers are set via
WebHttpRequest.Headers
. This is a value/pair list of HTTP options. Default, the option CacheControl
is set to no-cache
When a HTTP POST
command is execute, the POST
data can be set via the
WebHttpRequest.PostData
property.
By default WebHttpRequest.TimeOut
is zero, which means there is no time-out value. When
wanting to set a time-out value, WebHttpRequest.TimeOut
sets the time-out in milliseconds.
Finally, the URL
for performing the HTTP request is set via WebHttpRequest.URL: string;
When the HTTP request is successful, the OnResponse
event is triggered. When it fails, the
event OnAbort
is triggered.
When the request is successful, the request response is returned as event parameter of the
OnResponse
event.
procedure TForm1.WebHttpRequest1Response(Sender: TObject; AResponse:
string);
begin
ShowMessage('server response:' + AResponse);
end;
When the response comes as JSON, the JSON parser with a similar interface as the standard Delphi JSON parser can be used:
The following example shows how the response can be parsed as a JSON array:
procedure TForm1.WebHttpRequest1Response(Sender: TObject; AResponse:
string);
var
JS: TJSON;
JA: TJSONArray;
JO: TJSONObject;
i: integer;
begin
JS := TJSON.Create;
JA := TJSONArray(JS.Parse(AResponse));
for i := 0 to JA.Count - 1 do
begin
JO := TJSONObject(JA.Items[i]);
WebListBox1.Items.Add(JO.GetJSONValue('prop'));
end;
end;
An alternative way to handle the response is via an anonymous method. The signature of this anonymous method is declared as:
The same example handled via an anonymous method as such becomes:begin
WebHttpRequest1.URL :=
'http://www.tmssoftware.biz/tmsweb/music.json';
WebHttpRequest1.Execute(
procedure(AResponse: string; AReq: TJSXMLHttpRequest)
var
js: TJSON;
ja: TJSONArray;
jo: TJSONObject;
i: integer;
begin
js := TJSON.Create;
try
ja := TJSONArray(js.Parse(AResponse));
ShowMessage('Retrieved items:' +inttostr(ja.Count));
for i := 0 to ja.Count - 1 do
begin
jo := TJSONObject(ja.Items[i]);
WebListBox1.Items.Add(jo.GetJSONValue('title'));
end;
finally
js.Free;
end;
end
);
end;
And finally, there is also the promise/await based approach that permits writing code as if it is sequential but still, underlying it is asynchronously executed.
procedure TForm1.WebButton1Click(Sender: TObject);
var
req: TJSXMLHttpRequest;
begin
WebHttpRequest1.URL := 'data.json';
try
req := await(TJSXMLHttpRequest, WebHttpRequest1.Perform());
showmessage(string(req.response));
except
// handle failure to execute request here
end;
end;
Note: do not forget to mark the method WebButton1Click()
in the form declaration as async:
The same promise based approach can also be used to determine the size of a resource at a specified URL
.
This code shows how to get the size first and then use the OnProgress
to track the progress of a HTTP request
.
procedure TForm1.WebButton1Click(Sender: TObject);
var
sz: int64;
begin
WebHttpRequest1.URL := 'http://myserver/largeresource.zip';
sz := await(integer, WebHttpRequest1.GetSize);
WebProgressBar1.Max := sz;
await(string, WebHttpRequest1.Perform);
end;
procedure TForm1.WebHttpRequest1Progress(Sender: TObject; Position,
Total: Int64);
begin
WebProgressBar1.Position := Position;
end;
Properties for TWebHttpRequest
Property | Description |
---|---|
Command | Sets the HTTP command type to execute. This can be httpCUSTOM , httpGET , httpPOST , httpDELETE , httpHEAD , httpPUT |
CustomCommand | Sets the custom HTTP command name |
Headers | StringList holding optional header parameters to pass along with the HTTP command |
Password | For authenticated HTTP requests, sets the password to be used |
PostData | Sets the data to be posted along with a httpPOST command as string |
ResponseType | Sets the expected response type for the request. Default this is a text response. Types are: rtDefault : default server response typertText : text responsertBlob : blob containing binary datartJSON : JavaScript object resulting from parsing a JSON datartDocument : HTML documentrtArrayBuffer : JavaScript array buffer |
TimeOut | Sets the timeout value (in milliseconds). This is the time after which the request should abort when not getting a response from the server |
URL | URL for performing the HTTP request |
User | For authenticated HTTP requests, sets the username to be used |
Methods for TWebHttpRequest
Method | Description |
---|---|
Execute | Executes the HTTP request. An optional anonymous method can be used to catch the response |
GetSize: TJSPromise | Async method to fetch the size of a resource |
Perform: TJSPromise | Async method that can be used with await() to execute the HTTP request |
Events for TWebHttpRequest
Event | Description |
---|---|
OnAbort | Event triggered when the HTTP request was aborted |
OnError | Event triggered when an error occurred with the HTTP request |
OnProgress | Event triggered during HTTP execution to indicate progress. Note that due to the nature of server, the total size might not always be returned. Use the GetSize() first if this is the case. |
OnRequestResponse | Event triggered when a response for the HTTP request was received. This event returns both the response as string as well as the JavaScript response object |
OnResponse | Event triggered when a response for the HTTP request was received. This event returns the response as string |
OnTimeOut | Event triggered when a timeout happened for the HTTP request |