0

I need to authorize via link "https://mysite.sexy/sessionid?login=abc&password=abc" and I got TidHttp and TIdSSLIOHandlerSocketOpenSSL connected both.

I send a query:

http.get("https://mysite.sexy/sessionid?login=abc&password=abc");

but instead of getting any response, after some seconds, I get this exception: "HTTP/1.1 401 Unauthorized."

I had a search over web and got these solutions:

http.Request.UserName :=  'abc';
http.Request.Password := 'abc';
http.Request.UserAgent := 'Mozilla/5.0 (X11; U; Linux i686; cs-CZ; rv:1.7.12) Gecko/20050929';

but still it doesn't help anyhow. However a response from a web-site via Chrome-browser doens't occur as an exception and just retrieve error code and description in JSON format:

{"Code":4,"Desc":"Invalid user login or password"}

So this response is what I'm waiting for, but get only exception and thread stops. Please, give directions! Delphi XE3.

notricky
  • 179
  • 1
  • 2
  • 18

1 Answers1

3

This is normal for Indy. It throws exceptions for non-successful responses like 401. You need to catch the exception and then check the response text, if you're really interested in the response text. (Typically, you're not, because the response code alone tells you all you need to know.) When you get an exception, the response text will be in the exception's ErrorMessage property.

try
  x := http.get("https://mysite.sexy/sessionid?login=abc&password=abc");
except
  on E: EIdHTTPProtocolException do begin
    if E.ErrorCode = 401 then
      x := E.ErrorMessage
    else
      raise;
  end;
end;

Setting the authorization properties of the request object apparently doesn't help because your server doesn't use standard HTTP authentication. Otherwise, Indy would have handled the 401 response and resent the request with the password automatically.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
  • Oh I was so close to it ;) I just used to check E.ErrorCode instead of ErrorMessage. Through a debugging mode it is seen, that SSLIO holds all content in itself, including headers and html body. I just didn't know how to get it. Well, that solves the problem, but may cause some problems in case, if other header comes instead of 401. I just need to handle such problems... – notricky Feb 24 '14 at 14:12
  • FYI, `TIdHTTP` handles 401 and 407 internally, triggering `OnSelect(Proxy)Authorization` and `On(Proxy)Authorization` events each time, until `TIdHTTP.MaxAuthRetries` is exceeded. You also need to make sure that the `hoInProcessAuth` flag is enabled in the `TIdHTTP.HTTPOptions` property. – Remy Lebeau Feb 25 '14 at 20:05