arrays - delphi 将文件作为字节数组发送到 Rest 服务

标签 arrays rest delphi delphi-10.1-berlin

我使用的是 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 作为输入的重载。您可以使用 TBytesStreamTBytes 包装到 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/

相关文章:

javascript - 数组 .includes() 给出意外行为

java - 在 foreach 循环中直接转换

Java Jersey 声明式超链接 @Ref 注解的使用

asp.net - 回合制游戏 : Use SignalR or both SignalR and REST API?

c++ - 指向二维数组的指针

C#如何处理从android上传到C#的多部分文件

delphi - Delphi XE 中不再有 xercesxmldom 单元?

string - Delphi Pos 总是返回 0

delphi - 从 Tstringgrid 检索数据并将检索到的数据填充到包含 word 的图表中的快速方法

javascript - 使用JavaScript遍历嵌套数组元素