在荷兰(未来的英国也是如此),我们有一个用于计算沉积物的政府 API 服务 (AERIUS)。这是基于使用 JSON 格式的 HTTP REST 协议。我正在使用 Delphi Indy 10 版本的
TIdHTTP
,到目前为止,它对于这项服务运行得非常好。但是,文件需要发送到服务器的方式已经改变,从现在开始需要multipart/form-data
。
我得到的错误是:
http/1.1 415(不支持的媒体类型)
我从许多类似的问题中了解到必须设置
Accept
和ContentType
。然而,正如 @RemyLebeau 所说,最后一个关于文件发送部分是在 TIdMultPartFormDataStream
中完成的。
var
LParamToSend: TIdMultiPartFormDataStream;
const
cFileName = 'c:\...\filename.gml';
begin
LParamToSend := TIdMultiPartFormDataStream.Create;
// example on connect.aerius.nl/api "POST receptorSets", where the upload of this file is fine:
// curl -X POST "https://connect.aerius.nl/api/v7/receptorSets" -H "accept: application/json"
// -H "api-key: f6...c" -H "Content-Type: multipart/form-data"
// -F "receptorSet={"name": ... see below ...}" -F "filePart=@cFileName"
FHttp.HandleRedirects := True;
FHttp.Request.Accept := 'application/json';
FHttp.Request.CustomHeaders.AddValue('api-key', edtAPIcode.Text);
LParamToSend.AddFormField('receptorSet',
'{"name":"example","description":"testing","expectRcpHeight":false}');
LParamToSend.AddFile('filePart', cFileName);
try
edtMemo.Text := FHttp.Post('https://connect.aerius.nl/api/v7/receptorSets', LParamToSend);
except
on E: Exception do
edtMemo.Text := edtMemo.Text + e.Message;
end;
LParamToSend.Free;
end;
最后我自己找到了解决方案。由于这是我的第一个问题,我将分享答案,因此可能对其他人也有帮助。需要设置
ContentType
和 ContentTransfer
。无论如何,建议都是受欢迎的。
with LParamToSend.AddFormField('receptorSet',
'{"name":"example","description":"testing","expectRcpHeight":false}') do begin
ContentType := '';
ContentTransfer := '';
end;
LParamToSend.AddFile('filePart', cFileName).ContentTransfer := '';