Send an HTTP GET from Delphi and own the response lifetime
Use THTTPClient.Get for a synchronous HTTP GET in a Delphi console application or controlled worker. Keep the client alive while you inspect its IHTTPResponse, check the status code and decode the content. A completed request does not imply a successful application response.
The example targets Delphi 13 on Windows and uses a small loopback fixture. Its plain HTTP address is appropriate only for that local test. Real remote endpoints should use HTTPS with the platform's normal certificate validation.
Create the client
Create a console application named GetDemo and replace its project source with this program. Pass the request URL as its first argument.
program GetDemo;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Net.HttpClient;
procedure Run(const URL: string);
var
Client: THTTPClient;
Response: IHTTPResponse;
begin
Client := THTTPClient.Create;
try
Client.ConnectionTimeout := 5000;
Client.ResponseTimeout := 10000;
Client.HandleRedirects := False;
Response := Client.Get(URL);
Writeln('HTTP ', Response.StatusCode);
if (Response.StatusCode < 200) or (Response.StatusCode >= 300) then
raise Exception.CreateFmt('Request failed with HTTP %d.', [Response.StatusCode]);
Writeln(Response.ContentAsString.TrimEnd);
finally
Response := nil;
Client.Free;
end;
end;
begin
try
if ParamCount <> 1 then
raise Exception.Create('Usage: GetDemo <URL>');
Run(ParamStr(1));
except
on E: Exception do
begin
Writeln('Error: ', E.Message);
ExitCode := 1;
end;
end;
end.
The response is an interface reference. Assigning nil releases this reference before the client is freed. Do not call Free on the interface. If you pass your own stream to Get, keep that stream alive for the request and follow its separate ownership contract.
Run a controlled endpoint
With Python 3 installed, save this fixture as fixture.py and run python fixture.py in a separate terminal. It binds only to loopback and serves fixed small bodies.
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
ok = self.path == "/hello"
body = b"Hello from Delphi fixture.\n" if ok else b"Not found.\n"
self.send_response(200 if ok else 404)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 8765), Handler).serve_forever()
Run GetDemo.exe http://127.0.0.1:8765/hello. The expected output is:
HTTP 200
Hello from Delphi fixture.
Requesting /missing should print HTTP 404, followed by Error: Request failed with HTTP 404., and return process exit code 1. Stop the fixture when finished. This server is a test aid, not a production web service.
Separate status, transport and timeout failures
The example disables automatic redirects so a 3xx response remains visible. Enable redirects only when your endpoint contract permits them. A network or TLS failure can raise an exception before a response exists, while a 404 is a received response with an unsuccessful status.
Timeout properties are measured in milliseconds. ResponseTimeout concerns response progress and is not a general wall-clock budget for every phase of an arbitrary workflow. If the application needs cancellation or a total deadline, design and test that separately with the chosen platform HTTP implementation.
ContentAsString uses response charset information when no encoding is supplied. This fixture declares UTF-8. The TrimEnd call is only for the displayed demonstration text and must not be used when trailing whitespace is meaningful data.
The whole response is buffered here because the fixture is small. For large or untrusted downloads, use an appropriate destination stream and enforce a size policy while receiving. Do not block the VCL main thread with a slow synchronous request. Publish worker results back to the UI only while the intended receiver remains alive, and never disable certificate validation to make an HTTPS error disappear.
References
Question provenance
This article addresses What's the simplest way to call Http GET url using Delphi? , asked by Mohammed Nasman on Stack Overflow. The source question is licensed under CC BY-SA 3.0 . The explanation and examples here are newly authored for current Delphi. No answer text or code is reproduced.
Author: Herman Schoenfeld