rest - 如何在Delphi REST中发布ContentType为 'multipart/form-data'的数据?

标签 rest delphi https firemonkey indy

我正在尝试使用 multipart/form-data 作为内容类型向 REST API 发送请求。

我总是收到“HTTP/1.1 500 Internal Error”作为响应。

我尝试向需要 application/x-www-form-urlencoded 的方法发送请求,但取得了成功。

如何使用 multipart/form-data 从我的 API 获得成功响应?

这是我的代码:

procedure TForm10.Button1Click(Sender: TObject);
var
  RESTClient1: TRESTClient;
  RESTRequest1: TRESTRequest;
  strImageJSON : string;
  Input: TIdMultipartFormDataStream;
begin
  Input := TIdMultipartFormDataStream.Create;
  Input.Clear;
  Input.AddFormField('Email', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdb9b8aaaface3b5b58daca1a1a4aca3b7e3aea2a0e3b9bf" rel="noreferrer noopener nofollow">[email protected]</a>');
  Input.AddFormField('Password', 'xxxx');
  RESTClient1 := TRESTClient.Create('http://192.168.1.172:81/');
  RESTRequest1 := TRESTRequest.Create(nil);
  RESTRequest1.Method := TRESTRequestMethod.rmPOST;
  RESTRequest1.Resource := 'api/Mobile/MobileLoginControl';
  RESTRequest1.AddBody(Input,TRESTContentType.ctMULTIPART_FORM_DATA);
  RESTRequest1.Client := RESTClient1;
  RESTRequest1.Execute;
  strImageJSON := RESTRequest1.Response.Content;
end;

最佳答案

Embarcadero 的 REST 组件通过 TRESTRequest.AddParameter() 拥有自己的内置 multipart/form-data 功能方法:

procedure TForm10.Button1Click(Sender: TObject);
var
  RESTClient1: TRESTClient;
  RESTRequest1: TRESTRequest;
  strImageJSON : string;
begin
  RESTClient1 := TRESTClient.Create('http://192.168.1.172:81/');
  try
    RESTRequest1 := TRESTRequest.Create(nil);
    try
      RESTRequest1.Method := TRESTRequestMethod.rmPOST;
      RESTRequest1.Resource := 'api/Mobile/MobileLoginControl';
      RESTRequest1.AddParameter('Email', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcbcad8ddde91c7c7ffded3d3d6ded1c591dcd0d291cbcd" rel="noreferrer noopener nofollow">[email protected]</a>', TRESTRequestParameterKind.pkREQUESTBODY);
      RESTRequest1.AddParameter('Password', 'xxxx', TRESTRequestParameterKind.pkREQUESTBODY);
      RESTRequest1.Client := RESTClient1;
      RESTRequest1.Execute;
      strImageJSON := RESTRequest1.Response.Content;
    finally
      RESTRequest1.Free;
    end;
  finally
    RESTClient1.Free;
  end;
end;

您不需要使用 Indy 的 TIdMultiPartFormDataStream,特别是当您不使用 Indy 的 TIdHTTP 时。

关于rest - 如何在Delphi REST中发布ContentType为 'multipart/form-data'的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58377996/

相关文章:

SpringRestDoc SnippetException : Fields with the following paths were not found in the payload:

api - 带链接的 REST 资源表示,兼容 PUT 和 GET

http - 您可以将 Keep-Alive 与带有 HTTP 代理的 CONNECT 请求一起使用吗?

谷歌浏览器中的 ssl 错误...没有公钥?

c# 使用 Skydrive REST API 的 PUT 请求出现问题

xml - 导出到 Excel - 中间文件格式?

delphi - Delphi 4的代码分析工具

delphi - 有没有Delphi DFM 到Delphi 源代码的转换工具?

javascript - 解析单个对象 JSON 响应

c# - Web API Controller ,RESTful Web 方法。 (有 Angular )