将cURL格式转换为 Delphi

s4n0splo  于 2022-11-04  发布在  其他
关注(0)|答案(2)|浏览(160)

我需要在 Delphi 中模仿这个Curl命令,我该怎么做呢?

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

xxhby3vn1#

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;
hm2xizp9

hm2xizp92#

或者,使用Indy( 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;

相关问题