Sending GET and POST Requests with Delphi’s TNetHTTPClient and Retrieving Web Content
Delphi's TNetHTTPClient component provides a simple and flexible way to send GET and POST requests, pass query parameters, and work with custom headers and cookies. In this tutorial, we will look at how to perform basic HTTP communication, retrieve content from a web server, and handle common tasks such as sending form data and managing session cookies. These examples provide a practical foundation for integrating web services and REST APIs into your Delphi applications.
Creating the Form
Start by launching the Delphi IDE and creating a new project via
File → Windows VCL Application – Delphi.
On the form, place two TButton components, one TNetHTTPClient, and a TMemo.
These components will be used to send HTTP requests and display the server responses.
Writing the Code
Enter the following source code into the editor.
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Net.URLClient,
System.Net.HttpClient, System.Net.HttpClientComponent;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
NetHTTPClient1: TNetHTTPClient;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure NetHTTPClient1AuthEvent(const Sender: TObject;
AnAuthTarget: TAuthTargetType; const ARealm, AURL: string; var AUserName,
APassword: string; var AbortAuth: Boolean;
var Persistence: TAuthPersistenceType);
private
{ Private declarations }
public
{ Public declarations }
end;
//Class helper to allow deleting cookies
TCookieManagerHelper = class helper for TCookieManager
procedure DeleteCookie(i:Integer);
procedure DeleteAllCookies();
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses System.NetEncoding;
{TCookieManagerHelper}
procedure TCookieManagerHelper.DeleteCookie(i:Integer);
begin //Delete the i-th cookie
with self do
FCookies.Delete(i);
end;
procedure TCookieManagerHelper.DeleteAllCookies();
begin //Delete all cookies
with self do
FCookies.Clear;
end;
{TForm1}
procedure TForm1.Button1Click(Sender: TObject);
var strm:TMemoryStream; // Stream to store the server response content
res:IHTTPResponse; // HTTP response from the server
Header:TNetHeaders; // For generating custom headers
i:Integer;
Cookie:TCookie; // For creating cookies
AUrl:TURI;
b:TBytes;
GerParam:string; // For generating GET parameters
begin
strm:=TMemoryStream.Create;
try
//Set a custom User-Agent string
NetHTTPClient1.UserAgent:=
'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) '+
'AppleWebKit/605.1.15 (KHTML, like Gecko) '+
'Version/12.0 Mobile/15E148 Safari/604.1';
//Set a custom User-Agent string
NetHTTPClient1.AllowCookies:=True;
//Add cookies manually
NetHTTPClient1.CookieManager.AddServerCookie(
'cookie1=cookieValue1',
'http://localhost'
);
NetHTTPClient1.CookieManager.AddServerCookie(
'cookie2=cookieValue2',
'http://localhost'
);
//Add a cookie containing UTF‑8 Japanese text (URL‑encoded)
Cookie.Name:='cookie3';
b:=TEncoding.UTF8.GetBytes('UTF8の日本語をクッキーに入れてみる');
Cookie.Value:=System.NetEncoding.TURLEncoding.URL.EncodeBytesToString(b);
Cookie.Expires:=EncodeDate(2025,1,1);//Expiration date
Cookie.Domain:='.localhost'; //Domain
Cookie.Path:='/';
Cookie.Secure:=False; //Secure flag
Cookie.HttpOnly:=True; //HTTPOnly flag
AUrl.Create('http://localhost');
NetHTTPClient1.CookieManager.AddServerCookie(Cookie,AUrl);
//Create a custom header for Basic Authentication
SetLength(Header,1);
Header[0].Create(
'Authorization',
'Basic '+TNetEncoding.Base64.Encode('user:password')
);
//Build GET parameters
b:=TEncoding.UTF8.GetBytes('UTF8の日本語をGETで生成する');
GerParam:='getname='+
System.NetEncoding.TURLEncoding.URL.EncodeBytesToString(b);
//Build GET parameters
res:=NetHTTPClient1.Get(
'http://localhost/tnethttpclient_test.php?'+GerParam,
strm,Header
);
//Display the received content as UTF‑8 text
memo1.Lines.LoadFromStream(strm,TENcoding.UTF8);
memo1.Lines.Insert(0,'Received Content');
memo1.Lines.Add('--------------------------------');
//Display the charset (some servers may not send it)
memo1.Lines.Insert(0,'Character Encoding of Received Content');
memo1.Lines.Insert(1,res.ContentCharSet);
memo1.Lines.Insert(2,'--------------------------------');
//Display cookies added or modified by the server
memo1.Lines.Add('Cookies Set or Modified by the Server');
for i := 0 to res.Cookies.Count-1 do
begin
memo1.Lines.Add(
res.Cookies[i].Name+' : '+
System.NetEncoding.TURLEncoding.URL.Decode(res.Cookies[i].Value)
);
end;
memo1.Lines.Add('--------------------------------');
//Display all current cookies
memo1.Lines.Add('Current Cookies');
for i := 0 to Length(NetHTTPClient1.CookieManager.Cookies)-1 do
begin
memo1.Lines.Add(
'('+
NetHTTPClient1.CookieManager.Cookies[i].Domain+
NetHTTPClient1.CookieManager.Cookies[i].Path+
') '+
NetHTTPClient1.CookieManager.Cookies[i].Name+': '+
System.NetEncoding.TURLEncoding.URL.Decode(
NetHTTPClient1.CookieManager.Cookies[i].Value
)
);
end;
memo1.Lines.Add('--------------------------------');
//届いたヘッダーを出力する
memo1.Lines.Add('Received Headers');
for i := 0 to length(res.Headers)-1 do
begin
memo1.Lines.Add(
res.Headers[i].Name+':'+res.Headers[i].Value
);
end;
finally
strm.Free;
end;
//Delete the first cookie
//NetHTTPClient1.CookieManager.DeleteCookie(0);
//Delete the first cookie
NetHTTPClient1.CookieManager.DeleteAllCookies;
end;
procedure TForm1.Button2Click(Sender: TObject);
var stl:TStringList; //Holds POST parameters
strm:TMemoryStream; //Stream for server response content
res:IHTTPResponse; //HTTP response
i:Integer;
begin
//When sending a POST request
Memo1.Clear;
stl:=TStringList.Create;
strm:=TMemoryStream.Create;
try
stl.Add('postname1=値1'); //POST parameter
stl.Add('postname2=値2');
//WebサーバーにPOST接続する
res:=NetHTTPClient1.Post(
'http://localhost/tnethttpclient_test.php',
stl, //Post parameter
strm, //Response stream
TEncoding.UTF8, //Encoding of POST data
[] //Custom headers
);
//Display the received content as UTF‑8 text
memo1.Lines.LoadFromStream(strm,TENcoding.UTF8);
memo1.Lines.Insert(0,'Received Content');
memo1.Lines.Add('--------------------------------');
//Display the charset
memo1.Lines.Insert(0,'Character Encoding of Received Content');
memo1.Lines.Insert(1,' '+res.ContentCharSet);
memo1.Lines.Insert(2,'--------------------------------');
//Display all current cookies
memo1.Lines.Add('Current Cookies');
for i := 0 to Length(NetHTTPClient1.CookieManager.Cookies)-1 do
begin
memo1.Lines.Add(
'('+
NetHTTPClient1.CookieManager.Cookies[i].Domain+
NetHTTPClient1.CookieManager.Cookies[i].Path+
') '+
NetHTTPClient1.CookieManager.Cookies[i].Name+': '+
System.NetEncoding.TURLEncoding.URL.Decode(
NetHTTPClient1.CookieManager.Cookies[i].Value
)
);
end;
memo1.Lines.Add('--------------------------------');
//Display all received headers
memo1.Lines.Add('Received Headers');
for i := 0 to length(res.Headers)-1 do
begin
memo1.Lines.Add(
res.Headers[i].Name+':'+res.Headers[i].Value
);
end;
finally
stl.Free;
strm.Free;
end;
//Delete the first cookie
//NetHTTPClient1.CookieManager.DeleteCookie(0);
//Delete all cookies
NetHTTPClient1.CookieManager.DeleteAllCookies;
end;
procedure TForm1.NetHTTPClient1AuthEvent(const Sender: TObject;
AnAuthTarget: TAuthTargetType; const ARealm, AURL: string; var AUserName,
APassword: string; var AbortAuth: Boolean;
var Persistence: TAuthPersistenceType);
begin
//Basic authentication can also be handled in this event
if AnAuthTarget = TAuthTargetType.Server then
begin
AUserName:='user';
APassword:='password';
end;
end;
end.
Reference: PHP Source Code on the Web Server (localhost)
<?php //Save this file using UTF-8 encoding
//Output received cookies
if(count($_COOKIE)>0){
echo "Received cookies\r\n";
foreach($_COOKIE as $key=>$val){
echo ' '.$key.'='.$val."\r\n";
//file_put_contents(__DIR__.'/tnethttpclient.txt',$val."\r\n",FILE_APPEND);
}
}
//Output received GET or POST parameters
if(count($_REQUEST)>0){
echo "Received GET or POST parameters\r\n";
foreach($_REQUEST as $key=>$val){
echo ' '.$key.'='.$val."\r\n";
//file_put_contents(__DIR__.'/tnethttpclient.txt',$val."\r\n",FILE_APPEND);
}
}
//Output received Basic Authentication header
if(isset(getallheaders()['Authorization'])){
echo "Received Basic Authentication header\r\n";
echo " Authorization: ".getallheaders()['Authorization']."\r\n";
}
//Set cookies on the web server side
setCookie('cookie3','Set Cookie3 Value from WebServer');
setCookie('cookie4','Set Cookie4 Value from WebServer');
Running the Example
Run the application and click Button1 to send a GET request to the server. The response and related information will be displayed in the memo.
Clicking Button2 sends a POST request to the server, and the response will be shown in the same way.
Reference: HTTP Headers Sent and Received During a GET Request
HTTP headers sent to the server using the GET method
The highlighted red section shows the cookies included in the request.
Connection: Keep-Alive
Authorization: Basic dXNlcjpwYXNzd29yZA==
Cookie: cookie3=UTF8%E3%81%AE%E6%97%A5%E6%9C%AC%E8%AA%9E%E3%82%92%E3%82%AF%E3%83%83%E3%82%AD%E3%83%BC%E3%81%AB%E5%85%A5%E3%82%8C%E3%81%A6%E3%81%BF%E3%82%8B; cookie2=cookieValue2; cookie1=cookieValue1
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone ...omitted
Host: 192.168.1.2
HTTP headers received from the server using the GET method
The highlighted red section shows the cookies returned by the server.
Date: Tue, 08 Mar 2022 10:33:16 GMT
Server: Apache/2.4.27 (Win64) OpenSSL/1.1.0f PHP/7.2.7
X-Powered-By: PHP/7.2.7
Set-Cookie: cookie3=Set+Cookie3+Value+from+WebServer
Set-Cookie: cookie4=Set+Cookie4+Value+from+WebServer
Content-Length: 287
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
