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

时间:2019-10-14 13:35:55

标签: 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', 'tugba.xx@allianz.com.tr');
  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;

1 个答案:

答案 0 :(得分:1)

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', 'tugba.xx@allianz.com.tr', 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时。