我已经阅读了许多关于使用idHTTP发送数据的相关帖子,但我仍然无法管理它。我用这个代码:
更新
procedure TTabbedForm.SpeedButton1Click(Sender: TObject);
var
fName : string;
mStream : TMemoryStream;
begin
fName := 'image.jpg';
mStream := TMemoryStream.Create;
myImage.Bitmap.SaveToStream(mStream);
mStream.Position := 0;
try
IdHTTP1.Request.ContentType := 'application/octet-stream';
IdHTTP1.PUT('http://www.example.com/'+fName, mStream);
finally
mStream.free;
end;
end;
但我收到错误“方法不允许”。我做错了什么,拜托?
要上传到Google云端硬盘,需要执行一些其他步骤。例如,HTTP POST请求必须包含一个身份验证令牌,而该令牌仅在身份验证后提供给您(使用Google帐户登录)。对于Google云端硬盘,您还必须使用需要SSL库(如OpenSSL)的安全连接(https)。
来自API文档的Example:
POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media HTTP/1.1
Content-Type: image/jpeg
Content-Length: [NUMBER_OF_BYTES_IN_FILE]
Authorization: Bearer [YOUR_AUTH_TOKEN]
[JPEG_DATA]
此处记录了Google云端硬盘的文件简单上传API:
https://developers.google.com/drive/api/v3/simple-upload
更新
试试这个例子,它需要一个有效的身份验证令牌:
procedure TDriveAPITest.Run;
var
PostData: TStream;
Response: string;
begin
PostData := TFileStream.Create('test.png', fmOpenRead or fmShareDenyWrite);
try
IdHTTP := TIdHTTP.Create;
try
IdHTTP.HTTPOptions := IdHTTP.HTTPOptions + [hoNoProtocolErrorException];
IdHTTP.Request.CustomHeaders.Values['Authorization'] := 'Bearer [YOUR_AUTH_TOKEN]';
Response := IdHTTP.Post('https://www.googleapis.com/upload/drive/v3/files?uploadType=media', PostData);
if IdHTTP.ResponseCode = 200 then begin
WriteLn('Response: ' + Response);
end else begin
WriteLn('Error: ' + IdHTTP.ResponseText);
end;
finally
IdHTTP.Free;
end;
finally
PostData.Free;
end;
end;
输出:
Error: HTTP/1.0 401 Unauthorized