HTTP / 1.1 idHTTP error 401 Unauthorized

2

Good morning,   I already tested several tips and solutions on this subject here in the forum and outside too, I have been trying for 5 days to make a post using idHttp with delphi Berlin.

This is my code;

procedure TfrmPlaPSync.Button8Click(Sender: TObject);
var
  HTTP: TIdHTTP;
  RequestBody: TStream;
  ResponseBody: string;
begin
  HTTP := TIdHTTP.Create;
  try
    try
      RequestBody := TStringStream.Create('{"cod_regiao": "41", "nome": "NORTE"}',TEncoding.UTF8);
      try
        HTTP.Request.Accept := 'application/json';
        HTTP.Request.ContentType := 'application/json';
        HTTP.Request.BasicAuthentication := true;
        HTTP.Request.Username := 'robinho';
        HTTP.Request.Password := 'rb823321';
        HTTP.Request.Connection  := 'keep-alive';
        HTTP.Request.UserAgent   := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36';
        HTTP.Request.AcceptEncoding := 'gzip, deflate';
        HTTP.Request.AcceptLanguage := 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4';
        HTTP.Request.CacheControl := 'no-cache';

        ResponseBody := HTTP.Post('http://localhost:888/api/millenium/regioes/inclui',
          RequestBody);
        Memo2.Lines.Add(ResponseBody);
        Memo2.Lines.Add(HTTP.ResponseText);
      finally
        RequestBody.Free;
      end;
    except
      on E: EIdHTTPProtocolException do
      begin
        Memo2.Lines.Add(E.Message);
        Memo2.Lines.Add(E.ErrorMessage);
      end;
      on E: Exception do
      begin
        Memo2.Lines.Add(E.Message);
      end;
    end;
  finally
    HTTP.Free;
  end;
  ReportMemoryLeaksOnShutdown := True;
end;

The API requests a basic authentication that I am passing in the header, however I am having the following error:

HTTP/1.1 401 Unauthorized
    
asked by anonymous 08.05.2017 / 14:23

1 answer

1

Friend, I think what is missing is the following:

IdHTTP.Request.Clear;
IdHTTP.Request.CustomHeaders.Clear;
IdHTTP.Request.CustomHeaders.AddValue('Authorization', 'Basic ' + seu_token_autorizacao);

See only the header name and adapt to your need. For me, it worked.

Hugs!

    
09.08.2018 / 20:35