HttpPost/SSL
function HttpPost(URL, Params: string; Headers: TStringList; var ResultCode: integer; var Result: string; TimeoutMsec: integer): boolean; overload;
function HttpPost(URL, Params: string; Headers: TStringList; var ResultCode: integer; var Result: TMemoryStream; TimeoutMsec: integer): boolean; overload;
These functions send an HTTP POST request (with optional parameters) to a remote web server and returns the numeric result code as well as the actual data stream returned by the web server.
This is an overloaded function: the data stream can be returned either into a string variable (very handy when retrieving HTML web pages or XML) or as a TMemoryStream (useful when downloading binary streams like images, zip archives, executables, and so on).
Parameters
URL |
The full URL to the web page/script to be called (both HTTP and HTTPS are supported here) |
Params |
A formatted string of (optional) parameters encoded with the HttpEnc function |
Headers |
(Optional) a string list of additional headers to be sent to the web server - can be nil if no additional headers are required |
ResultCode |
An integer variable that, after the call, will contain the result code sent by the remote web server |
Result |
A string or TMemoryStream variable that, after the call, will contain the data returned by the web server |
TimeoutMSec |
An integer value that specifies the request timeout in milliseconds (can be omitted, defaults to 5000) |
Return value
Boolean |
Returns True if the call succeeds (regardless of the result code), otherwise it will return False (for instance when the web server is unreachable) |
Examples
// Sample HTTP POST as string
var
ResCode: integer;
Params, Result: string;
AddHead: TStringList;
begin
AddHead := TStringList.Create;
Params := 'first_param=' + HttpEnc('my first parameter')
+ '&' + 'second_param=' + HttpEnc('my second parameter')
+ '&' + 'third_param=' + HttpEnc('my third parameter');
if HttpPost('http://www.yourwebsite.com/form.php', Params, AddHead, ResCode, Result) then
begin
StringToFile(IntToStr(ResCode)+#13#10#13#10, 'c:\test\dbg_httpget.txt');
AppendStringToFile(Result, 'c:\test\dbg_httppost.txt');
end;
AddHead.Free;
end.
// Sample HTTP POST as binary stream (TMemoryStream)
var
ResCode: integer;
Params: string;
Result: TMemoryStream;
begin
Params := 'first_param=' + HttpEnc('my first parameter')
+ '&' + 'second_param=' + HttpEnc('my second parameter')
+ '&' + 'third_param=' + HttpEnc('my third parameter');
Result := TMemoryStream.Create;
try
if HttpPost('http://srv.yourwebsite.com/form.php', Params, nil, ResCode, Result) then
Result.SaveToFile('c:\test\returned_image.png');
finally
Result.Free;
end;
end.