Home > Mobile >  Convert cURL format to Delphi
Convert cURL format to Delphi

Time:08-18

I need to mimic this Curl command in Delphi, how can I do it?

curl -X POST \
https://api.encurtador.dev/encurtamentos \
-H 'content-type: application/json' \
-d '{ "url": "https://google.com" }'

CodePudding user response:

uses
  REST.Client, REST.Types;

function cUrlCall: string;
begin
  var client := TRESTClient.Create('https://api.encurtador.dev');
  try
    var request := TRESTRequest.Create(client);
    request.Method := rmPOST;
    request.Resource := 'encurtamentos';
    request.AddBody('{ "url": "https://google.com" }', TRESTContentType.ctAPPLICATION_JSON);
    request.Execute;
    Result := request.Response.Content;
  finally
    client.Free;
  end;
end;

CodePudding user response:

Alternatively, using Indy (which is preinstalled in Delphi):

uses
  ..., Classes, SysUtils, IdHTTP;

var
  Http: TIdHTTP;
  PostData: TStringStream;
  Resp: string;
begin
  Http := TIdHTTP.Create;
  try
    PostData := TStringStream.Create('{ "url": "https://google.com" }', TEncoding.UTF8);
    try
      Http.Request.ContentType := 'application/json';
      Resp := Http.Post('https://api.encurtador.dev/encurtamentos', PostData);
    finally
      PostData.Free;
    end;
  finally
    Http.Free;
  end;
end;
  • Related