[fpc-pascal] TFPHttpClient & TFPHttpServer

duilio foschi octopushole at gmail.com
Tue Jan 3 23:08:10 CET 2023


I would like to write some code where a TFPHttpClient component sends
a minimal json payload to a TFPHttpServer that (reads the payload).

The working of the TFPHttpClient component is clear enough, while its
counterpart TFPHttpServer proves rather obscure to me.

TFPHttpClient
===========
Page  https://wiki.freepascal.org/fphttpclient
contains complete and clear code:


var
  Client: TFPHttpClient;
  Response: TStringStream;
  Params: string = '{"Name": "John", "Age": 32}';
begin
  Client := TFPHttpClient.Create(nil);
  Client.AddHeader('User-Agent', 'Mozilla/5.0 (compatible; fpweb)');
  Client.AddHeader('Content-Type', 'application/json; charset=UTF-8');
  Client.AddHeader('Accept', 'application/json');
  Client.AllowRedirect := true;
  Client.UserName := USER_STRING;
  Client.Password := PASSW_STRING;
  Client.RequestBody := TRawByteStringStream.Create(Params);
  Response := TStringStream.Create('');
  try
    try
      Client.Post(TheURL, Response);
      Writeln('Response Code: ' +
IntToStr(Client.ResponseStatusCode)); // better be 200
    except on E: Exception do
      Writeln('Something bad happened: ' + E.Message);
    end;
  finally
    Client.RequestBody.Free;
    Client.Free;
    Response.Free;
  end;

I reckon I need to set - say-
TheURL:='http://localhost:9200';
here


TFPHTTPServer
=============

say we use
TTestHTTPServer=class(TFPHTTPServer);
for our server,

I understand that all action takes place inside procedure
DataModuleRequest (so far so good):

procedure TTestHTTPServer.DataModuleRequest(Sender: TObject; ARequest: TRequest;
 AResponse: TResponse; var Handled: Boolean);
begin
   //
end;

Q1: how can I create an object of type jsondata from ARequest?

Q2: can I get a UTF8 string from ARequest?

Q3: TFPHTTPServer has property Port. I reckon it will be set to 9200
here. Is it correct?

Q4: TFPHTTPServer has property Address. I reckon it will be set to
'localhost' here. Is it correct?

Q5: TFPHTTPServer has no property Username and Password. How do I
check the values I set in the corresponding properties of
TFPHTTPClient?

Q6: what is the use of parameter Handled?

I apologize if I overlooked the relevant documentation.

Thank you

Peppe


More information about the fpc-pascal mailing list