Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there way to get the final URL after redirects using WinHTTP in Delphi?

I can use the following code to easily get the HTML source from the URL, but how can I get the actual URL itself? Because sometimes the initial URL goes through some redirects and the actual URL is not the same and I would like to capture it for usage. I cannot seem to find any good documentation on the usage of methods or properties for winHTTP in Delphi. Thanks!

var http: variant;
begin
 http:=createoleobject('WinHttp.WinHttpRequest.5.1');
 http.open('GET', 'http://URLtoWebsite.com', false);
 http.send;
 showmessage(http.responsetext);
end;
like image 402
gts6 Avatar asked Oct 27 '25 05:10

gts6


1 Answers

You can use something like this

function GetFinalURL(const AMainURL: string): string;
var
  http: Variant;
begin
  Result := '';
  http := CreateOleObject('WinHttp.WinHttpRequest.5.1');
  http.Option(6) := False;
  http.open('GET', AMainURL, false);
  http.send;
  if http.Status = 302 then
    Result := http.getResponseHeader('Location')
  else
  Result := AMainURL;
end;

Another way using Indy

function GetFinalURL(const AMainURL: string): string;
var
  idHTTP: TIdHTTP;
begin
  Result := '';
  idHTTP := TIdHTTP.Create(nil);
  try
    idHTTP.HandleRedirects := True;
    try
      idHTTP.Get(AMainURL);
      Result := idHTTP.Request.URL;
    except
    end;
  finally
    idHTTP.Free;
  end;
end;
like image 181
RepeatUntil Avatar answered Oct 29 '25 18:10

RepeatUntil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!