Reputation: 3238
I have a web address that will take me to a different URL address. This is MOST likely through a URL redirection. I need a way of taking the initial URL and determining what the URL of the "end result" page would be. I have looked around, and the Indy component TIdHTTP has been recommended. Is this the best (aka simplest/easiest) way to do this? As I have little experience with this type of coding, if anyone has sample code to share, it would be appreciated.
As an example, here is a starting URL that I have...
Thanks
Upvotes: 0
Views: 1157
Reputation: 1659
I'd suggest performing a simple get request and handling the OnRedirect event to save the last address that has been redirected to. You could also save intermediate addresses in case this is needed.
I wrote a small class to handle that, in the scope of your project you would probably add those methods to the class that needs the result though rather than encapsulating it.
TRedirectTester = class
private
Address: string;
procedure RedirectProc(Sender: TObject; var dest: string;
var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
public
function RedirectionResult(InitialURL: string): string;
end;
I defined a public function to return the final URL after redirection and a private procedure to assign to the OnRedirect event (hence the signature) and a variable to store the redirection destination.
Regarding the implentation, remember setting HandleRedirects
to true
to enable the redirections, the IOHandler
has to be assigned in order to be able to handle HTTPS. The method assigned to the OnRedirect
event will be called every time a redirect occurs, so we can save the destination.
procedure TRedirectTester.RedirectProc(Sender: TObject; var dest: string;
var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
begin
Address := dest;
end;
function TRedirectTester.RedirectionResult(InitialURL: string): string;
var IdHttp: TIdHTTP;
begin
Address := InitialURL;
IdHttp := TIdHTTP.Create(nil);
try
with IdHttp do
begin
HandleRedirects := true;
OnRedirect := RedirectProc;
IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create;
try
Get(InitialURL);
finally
IOHandler.Free;
end;
end;
finally
IdHttp.Free;
end;
Result := Address;
end;
Upvotes: 1