Oleg Adibekov
Oleg Adibekov

Reputation: 41

What's wrong with a request to Dropbox?

I have valid access token to Dropbox account (API v2), Delphi 7 and, Indy 10. When I try to use this token I have exception 'HTTP/1.1 400 Bad Request'. I look at Dropbox API v2 and can't understand: what's wrong with the request?

procedure TDropboxSaveFilterForm.TestButtonClick(Sender: TObject);
const
  AccessToken = 'Hq7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var
  IdHTTP: TIdHTTP;
  Source: TStringList;
  Res, URL: WideString;
begin
  Source := TStringList.Create;
  IdHTTP := TIdHTTP.Create(nil);
  IdHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
  URL := 'https://api.dropboxapi.com/2/files/list_folder' + '?' +
         'Authorization=Bearer ' + AccessToken;
  Res := IdHTTP.Post(URL, Source);
  Source.Free;
end;

New code with the header, error the same :-(. According to Indy: Request Specifies the header values to send to the HTTP server.

procedure TDropboxSaveFilterForm.TestHeaderButtonClick(Sender: TObject);
const
  AccessToken = 'Hq7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  URL = 'https://api.dropboxapi.com/2/files/list_folder';
var
  IdHTTP: TIdHTTP;
  Source: TStringList;
  Head, Res: WideString;
  Stream: TMemoryStream;
begin
  Source := TStringList.Create;
  IdHTTP := TIdHTTP.Create(nil);
  IdHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
  Head := 'Authorization: Bearer ' + AccessToken;
  Stream := TMemoryStream.Create;
  Stream.Write(Head, Length(Head));
  Stream.Position := 0;
  IdHTTP.Request.Source := Stream;
  Res := IdHTTP.Post(URL, Source);
  Source.Free;
end;

Upvotes: 1

Views: 657

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595702

You are trying to put the authorization data in the request URL and in the request body. You should put it in the request headers instead. Use the TIdHTTP.Request.CustomHeaders property to send a custom Authorization header value, eg:

procedure TDropboxSaveFilterForm.TestHeaderButtonClick(Sender: TObject);
const
  AccessToken = 'Hq7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  URL = 'https://api.dropboxapi.com/2/files/list_folder';
var
  IdHTTP: TIdHTTP;
  Source: TStringStream;
  Res: String;
  Stream: TMemoryStream;
begin
  Source := TStringStream.Create('JsonParamsHere');
  try
    IdHTTP := TIdHTTP.Create(nil);
    try
      IdHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
      IdHTTP.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + AccessToken;
      IdHTTP.Request.BasicAuthentication := False;
      IdHTTP.Request.ContentType := 'application/json';
      Res := IdHTTP.Post(URL, Source);
    finally
      IdHTTP.Free;
    end;
  finally
    Source.Free;
  end;
end;

Upvotes: 3

Related Questions