Home > OS >  Delphi Indy http.get with curl returns: unauthorized
Delphi Indy http.get with curl returns: unauthorized

Time:03-17

According to the suppliers data i should have:

  • Http type GET
  • Response type: application/json
  • Parameter: Authorization: bearer Token
  • Curl: curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer Token, 'http://localhost:8080/api/v1/doors'
  • Request URL: 'http://localhost:8080/api/v1/doors'

I have translated this to Delphi(Indy TidHttp):

procedure TForm42.Button2Click(Sender: TObject);
var
  resp: TMemoryStream;
begin
  resp := TMemoryStream.Create;
  try
    IdHTTP1.Request.Clear;
    IdHTTP1.Request.Accept := 'application/json';
    IdHTTP1.Request.BasicAuthentication := True;
    IdHTTP1.Request.CustomHeaders.FoldLines := False;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer '   TokenStr;
    IdHTTP1.Get('http://10.10.1.62:8080/api/v1/doors', resp);
    resp.Position := 0;
    memCall.Lines.LoadFromStream(resp);
  finally
    resp.Free;
  end;
end;

I read a lot about it here, so finally i also added 'foldlines (Adding custom header to TIdHttp request, header value has commas) I also tried 'X-Authorization' as parameter, something i read from R. Lebeau, but the only reaction i get is an errordialog saying '401 unauthorized'.

I'm sure about the Token string (-> 'bearer ' TokenStr) because i get an answer when putting the string in the suppliers trial.

Does someone have an idea what i'm doing wrong?

CodePudding user response:

Request.BasicAuthentication should be False not True when using custom authentications.

And you don't need to set CustomHeaders.FoldLines as TIdHTTP already disables folding by default (it wasn't disabled by default at the time the other question was posted).

Otherwise, the rest of the code looks fine.

Though, I would suggest specifying TEncoding.UTF8 on the call to LoadFromStream()), eg:

procedure TForm42.Button2Click(Sender: TObject);
var
  resp: TMemoryStream;
begin
  resp := TMemoryStream.Create;
  try
    IdHTTP1.Request.Clear;
    IdHTTP1.Request.Accept := 'application/json';
    IdHTTP1.Request.BasicAuthentication := False;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer '   TokenStr;
    IdHTTP1.Get('http://10.10.1.62:8080/api/v1/doors', resp);
    resp.Position := 0;
    memCall.Lines.LoadFromStream(resp, TEncoding.UTF8);
  finally
    resp.Free;
  end;
end;

Or, using the overload of TIdHTTP.Get() that returns a string:

procedure TForm42.Button2Click(Sender: TObject);
begin
  IdHTTP1.Request.Clear;
  IdHTTP1.Request.Accept := 'application/json';
  IdHTTP1.Request.BasicAuthentication := False;
  IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer '   TokenStr;
  memCall.Text := IdHTTP1.Get('http://10.10.1.62:8080/api/v1/doors');
end;
  • Related