Delphi HTTP POST JSON Example

Posted on August 31, 2020 at 11:52 am

Here is an example to POST JSON data with Delphi 10:

Reference: https://stackoverflow.com/a/24042633

Add these libraries in your uses:

idSSLopenSSL, idHttp, Json

Here is the example code to POST JSON data:

procedure TForm1.Button1Click(Sender: TObject);
var
  JsonStr: string;
  sResponse: string;
  JsonToSend: TStringStream;
  HTTP1: TidHTTP;
  F: TJSONObject;
begin
  Button1.Enabled := False;
  memoResponse.Lines.Clear;
  memoRequest.Lines.Clear;
 
  F := TJSONObject.Create;
  F.AddPair('applicationId', edApplication.Text);
  F.AddPair('applicationPassword', edPassword.Text);
  F.AddPair('accountId', edAccount.Text);
 
  JsonStr := F.ToJSON;
 
  memoRequest.Text := JsonStr;
 
  JsonToSend := TStringStream.Create(JsonStr, TEncoding.UTF8);
 
  HTTP1 := TIdHTTP.Create(nil);
 
  try
    HTTP1.Request.ContentType := 'application/json; charset=utf-8';
    HTTP1.Request.CharSet := 'utf-8';
    try
      sResponse := HTTP1.Post(edURL.Text, JsonToSend);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    FreeAndNil(HTTP1);
    FreeAndNil(JsonToSend);
    FreeAndNil(F);
  end;
 
  memoResponse.Text := sResponse;
 
  Button1.Enabled := True;
end;

You’ll need to place OpenSSL DLLs in your application.exe folder:

libeay32.dll
ssleay32.dll

Here you can download the application source files:

delphi-post-json-example.zip

Updated on September 11, 2020 at 11:15 pm

Receive updates via email

Other Posts

Updated Posts