【问题标题】:Convert cURL format to Delphi将 cURL 格式转换为 Delphi
【发布时间】:2023-01-29 14:25:14
【问题描述】:

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

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

【问题讨论】:

  • 响应实际上取决于您拥有的 Dephi 版本。我解决了与旧版本的 Delphi (6) 类似的问题,只是将 Curl 作为一个单独的进程直接调用,读取结果代码并捕获输出。
  • 我使用德尔福 RAD 10.4

标签: delphi curl


【解决方案1】:
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;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      另一个研究 - 连接到 DROPBOX API https://en.delphipraxis.net

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-05
        • 2021-06-05
        • 1970-01-01
        相关资源
        最近更新 更多