在 Delphi 中使用 TIdHTTP 来模拟带有用户身份验证的 curl 命令

use TIdHTTP in Delphi to simulate curl command with user authentication

我正在尝试在 Delphi 中使用 TIdHTTP 来模拟以下 curl 操作:

curl -X POST -F "message={\"user_email\" : \"useremail@domain.com\" , \"user_password\" : \"UserPassword\"}" "https://esm-db.eu/esmws/generate-signed-message/1/query" > token.txt

服务器端的指导方针在:https://esm-db.eu/esmws/generate-signed-message/1/query-options.html

成功的 curl 连接的详细输出如下:

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 193.206.88.90...
* TCP_NODELAY set
* Connected to esm-db.eu (193.206.88.90) port 443 (#0)
* schannel: SSL/TLS connection with esm-db.eu port 443 (step 1/3)
* schannel: checking server certificate revocation
* schannel: sending initial handshake data: sending 174 bytes...
* schannel: sent initial handshake data: sent 174 bytes
* schannel: SSL/TLS connection with esm-db.eu port 443 (step 2/3)
* schannel: failed to receive handshake, need more data
* schannel: SSL/TLS connection with esm-db.eu port 443 (step 2/3)
* schannel: encrypted data got 2954
* schannel: encrypted data buffer: offset 2954 length 4096
* schannel: sending next handshake data: sending 93 bytes...
* schannel: SSL/TLS connection with esm-db.eu port 443 (step 2/3)
* schannel: encrypted data got 258
* schannel: encrypted data buffer: offset 258 length 4096
* schannel: SSL/TLS handshake complete
* schannel: SSL/TLS connection with esm-db.eu port 443 (step 3/3)
* schannel: stored credential handle in session cache
> POST /esmws/generate-signed-message/1/query HTTP/1.1
> Host: esm-db.eu
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Length: 217
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------7682f54661679429
>
* schannel: client wants to read 102400 bytes
* schannel: encdata_buffer resized 103424
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: encrypted data got 54
* schannel: encrypted data buffer: offset 54 length 103424
* schannel: decrypted data length: 25
* schannel: decrypted data added: 25
* schannel: decrypted data cached: offset 25 length 102400
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: decrypted data buffer: offset 25 length 102400
* schannel: schannel_recv cleanup
* schannel: decrypted data returned 25
* schannel: decrypted data buffer: offset 0 length 102400
< HTTP/1.1 100 Continue
* schannel: client wants to read 102400 bytes
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: encrypted data got 924
* schannel: encrypted data buffer: offset 924 length 103424
* schannel: decrypted data length: 895
* schannel: decrypted data added: 895
* schannel: decrypted data cached: offset 895 length 102400
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: decrypted data buffer: offset 895 length 102400
* schannel: schannel_recv cleanup
* schannel: decrypted data returned 895
* schannel: decrypted data buffer: offset 0 length 102400
< HTTP/1.1 200 OK
< Server: nginx/1.10.3
< Date: Sun, 08 Nov 2020 23:20:51 GMT
< Content-Type: text/plain; charset=UTF-8
< Content-Length: 649
< Connection: keep-alive
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: POST, GET, OPTIONS
<
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

但是,对于 TIdHTTP,我不断收到 HTTP/1.1 400 Bad Request 错误。我做错了什么?

procedure TMainForm.HTTPGetTokenFile;
var
  IdHTTP: TIdHTTP;
  Params: TIdMultipartFormDataStream;
  LHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  try
    Params := TIdMultipartFormDataStream.Create;
    Params.AddFormField('message', '{\"user_email\" : \"useremail@domain.com\" , \"user_password\" : \"UserPassword\"}');
    try
      IdHTTP := TIdHTTP.Create(nil);
      try
        LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
        LHandler.SSLOptions.Method := sslvTLSv1;
        IdHTTP.IOHandler := LHandler;
        IdHTTP.Request.Accept := 'application/json, text/plain;q=0.9, text/html;q=0.8';
        IdHTTP.Request.ContentType := 'application/json';
        Memo1.Text := IdHTTP.Post('https://esm-db.eu/esmws/generate-signed-message/1/query', Params);
      finally
        IdHTTP.Free;
      end;
    finally
      Params.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Error: ' + E.ToString);
  end;
end;

更新:我删除了 JSON 中的 \ 个字符,但我仍然收到 HTTP/1.1 400 Bad Request 错误。

procedure TMainForm.HTTPGetTokenFile;
var
  IdHTTP: TIdHTTP;
  Params: TIdMultipartFormDataStream;
  LHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  try
    Params := TIdMultipartFormDataStream.Create;
    Params.AddFormField('message', '{"user_email" : "useremail@domain.com" , "user_password" : "UserPassword"}');
    try
      IdHTTP := TIdHTTP.Create(nil);
      try
        LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
        LHandler.SSLOptions.Method := sslvTLSv1;
        IdHTTP.IOHandler := LHandler;
        IdHTTP.Request.Accept := 'application/json, text/plain;q=0.9, text/html;q=0.8';
        IdHTTP.Request.ContentType := 'application/json';
        Memo1.Text := IdHTTP.Post('https://esm-db.eu/esmws/generate-signed-message/1/query', Params);
      finally
        IdHTTP.Free;
      end;
    finally
      Params.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Error: ' + E.ToString);
  end;
end;

TIdHTTP 的转储如下:

Stat Connected.
Sent 9/11/2020 4:36:55 ??: POST /esmws/generate-signed-message/1/query HTTP/1.0<EOL>Content-Type: multipart/form-data; boundary=--------110920163653921<EOL>Content-Length: 257<EOL>Host: esm-db.eu<EOL>Accept: application/json, text/plain;q=0.9, text/html;q=0.8<EOL>Accept-Encoding: identity<EOL>User-Agent: Mozilla/3.0 (compatible; Indy Library)<EOL><EOL>
Sent 9/11/2020 4:36:55 ??: ----------110920163653921<EOL>Content-Disposition: form-data; name="message"<EOL>Content-Type: text/plain<EOL>Content-Transfer-Encoding: quoted-printable<EOL><EOL>{"user_email" : "s.antoniou@seismosoft.com" , "user_password" : "passw=<EOL>ord"}<EOL>----------110920163653921--<EOL>
Recv 9/11/2020 4:36:55 ??: HTTP/1.1 400 Bad Request<EOL>Server: nginx/1.10.3<EOL>Date: Mon, 09 Nov 2020 14:36:56 GMT<EOL>Content-Type: text/html; charset=UTF-8<EOL>Content-Length: 121<EOL>Connection: close<EOL>Access-Control-Allow-Origin: *<EOL>Access-Control-Allow-Methods: POST, GET, OPTIONS<EOL><EOL>{"http_code": 400, "http_label": "Bad Request", "exit_message": "ERROR: improper specification / unrecognized parameter"}
Stat Disconnected.
Stat Disconnected.
Stat Disconnected.

好像AddFormField()函数的参数有70个字符的限制,最后3个字符好像被截掉了。我可以增加这个限制还是应该减小传递值的大小(例如通过删除不必要的空格)?

正如 Dave 在评论中提到的,您需要删除 JSON 数据中的 \ 个字符。 Delphi 不会像命令行处理器那样转义字符。 " 不是 Delphi 中的保留字符,因此无需转义 Delphi 字符串文字中的 " 字符。

另外,在旁注中,IdHTTP.Request.ContentType 的赋值在这种情况下是多余的,应该删除。 Post()'ing a TIdMultiPartFormDataStream 将用它自己的值覆盖 ContentType,忽略你分配的任何内容。

试试这个:

procedure TMainForm.HTTPGetTokenFile;
var
  IdHTTP: TIdHTTP;
  Params: TIdMultipartFormDataStream;
  LHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  try
    Params := TIdMultipartFormDataStream.Create;
    try
      Params.AddFormField('message', '{"user_email" : "useremail@domain.com" , "user_password" : "UserPassword"}');

      IdHTTP := TIdHTTP.Create(nil);
      try
        LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
        LHandler.SSLOptions.Method := sslvTLSv1;
        IdHTTP.IOHandler := LHandler;
        IdHTTP.Request.Accept := 'application/json, text/plain;q=0.9, text/html;q=0.8';
        Memo1.Text := IdHTTP.Post('https://esm-db.eu/esmws/generate-signed-message/1/query', Params);
      finally
        IdHTTP.Free;
      end;
    finally
      Params.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Error: ' + E.ToString);
  end;
end;

更新: 结果是 TIdMultiPartFormDataStreamQuoted-Printable 格式发送你的 JSON,其中一个“软”换行符每 70 个字符插入 JSON 的中间。显然,您的服务器不正确支持该编码。默认情况下,curl 不会使用 Quoted-Printable 进行网络表单提交,除非您明确告诉它这样做。

您可以通过以下任一方式在 TIdMultipartFormDataStream 中禁用 Quoted-Printable 编码:

  1. TIdFormDataField.ContentTransfer 属性 设置为 '7bit''8bit''binary'''(实际上与'7bit' 但没有通过 Content-Transfer-Encoding header 明确通知服务器),例如:
procedure TMainForm.HTTPGetTokenFile;
var
  IdHTTP: TIdHTTP;
  Params: TIdMultipartFormDataStream;
  LHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  try
    Params := TIdMultipartFormDataStream.Create;
    try
      with Params.AddFormField('message', '{"user_email" : "useremail@domain.com" , "user_password" : "UserPassword"}') do
      begin
        Charset := 'utf-8';
        ContentTransfer := '8bit';
      end;

      IdHTTP := TIdHTTP.Create(nil);
      try
        LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
        LHandler.SSLOptions.Method := sslvTLSv1;
        IdHTTP.IOHandler := LHandler;
        IdHTTP.Request.Accept := 'application/json, text/plain;q=0.9, text/html;q=0.8';
        Memo1.Text := IdHTTP.Post('https://esm-db.eu/esmws/generate-signed-message/1/query', Params);
      finally
        IdHTTP.Free;
      end;
    finally
      Params.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Error: ' + E.ToString);
  end;
end;
  1. 使用 AddFormField() 重载,使用 TStream 而不是 String。你可以把你的JSON变成TStringStream,例如:
procedure TMainForm.HTTPGetTokenFile;
var
  IdHTTP: TIdHTTP;
  Params: TIdMultipartFormDataStream;
  LHandler: TIdSSLIOHandlerSocketOpenSSL;
  LJSON: TStringStream;
begin
  try
    LJSON := TStringStream.Create('{"user_email" : "useremail@domain.com" , "user_password" : "UserPassword"}', TEncoding.UTF8);
    try
      Params := TIdMultipartFormDataStream.Create;
      try
        with Params.AddFormField('message', 'text/plain', 'utf-8', LJSON) do
          ContentTransfer := '8bit';
    
        IdHTTP := TIdHTTP.Create(nil);
        try
          LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
          LHandler.SSLOptions.Method := sslvTLSv1;
          IdHTTP.IOHandler := LHandler;
          IdHTTP.Request.Accept := 'application/json, text/plain;q=0.9, text/html;q=0.8';
          Memo1.Text := IdHTTP.Post('https://esm-db.eu/esmws/generate-signed-message/1/query', Params);
        finally
          IdHTTP.Free;
        end;
      finally
        Params.Free;
      end;
    finally
      LJSON.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Error: ' + E.ToString);
  end;
end;