我使用的是 Delphi 10.1 Berlin
我想使用 TRestRequest
将图像数据作为 TBytes
发送到 Rest 服务,但我找不到传递 TBytes
的方法到 TRestRequest.AddBody()
方法或任何其他方法。
POST http://myserver:1111//Openxxx/RecxxxLxxxPxxxx HTTP/1.1 Content-Type: text/json Host: myserver:1111 Content-Length: 28892 Expect: 100-continue Connection: Keep-Alive [255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,219,0,132,0,9, ... ... ... 130,130,252,168,127,164,63,164,41,109,204,245,62,106,51,135,12,146,63,255,217]
最佳答案
TRESTRequest.AddBody()
有一个接受 TStream
作为输入的重载。您可以使用 TBytesStream
将 TBytes
包装到 TStream
中。类。
procedure TForm1.Button1Click(Sender: TObject);
var
ABytes: TBytes;
AStream: TBytesStream;
begin
ABytes := ...;
try
AStream := TBytesStream.Create(ABytes);
RESTRequest1.AddBody(AStream, ctIMAGE_JPEG);
RESTRequest1.Execute;
finally
AStream.Free;
end;
end;
或者,使用 TRESTRequestParameterList.AddItem
相反,它具有 TBytes
的重载:
procedure TForm1.Button1Click(Sender: TObject);
var
ABytes: TBytes;
begin
ABytes := ...
RESTRequest1.Params.AddItem('body', ABytes, pkGETorPOST, [poDoNotEncode], ctIMAGE_JPEG);
RESTRequest1.Execute;
end;
话虽这么说,我发现 TRESTClient
过于复杂且有缺陷/限制。很多时候,Indy 的 TIdHTTP
更容易使用,例如:
procedure TForm1.Button1Click(Sender: TObject);
var
ABytes: TBytes;
AStream: TBytesStream;
begin
ABytes := ...;
try
AStream := TBytesStream.Create(ABytes);
IdHTTP1.Request.ContentType := 'image/jpeg';
IdHTTP1.Post('http://myserver:1111//Openxxx/RecxxxLxxxPxxxx', AStream);
finally
AStream.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
IdHTTP1.Request.ContentType := 'image/jpeg';
IdHTTP1.Post('http://myserver:1111//Openxxx/RecxxxLxxxPxxxx', 'image.jpg');
end;
关于arrays - delphi 将文件作为字节数组发送到 Rest 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42812071/