我正在尝试使用 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/