Matthew Hipkin

Follow HTTP redirects using Ararat Synapse

Here is a nice and simple way to follow HTTP redirects using the Ararat Synapse THTTPSend class.

program followredirect;
{$mode objfpc}{$H+}
uses Classes, SysUtils, httpsend;

function HTTPGet(URL: String; UserAgent: String): String;
var
  HTTP: THTTPSend;
  l: TStrings;
  i: Integer;
  realurl: String;
begin
  // Setup
  HTTP := THTTPSend.Create;
  HTTP.UserAgent := UserAgent;
  realurl := '';
  l := TStringList.Create;
  // Perform HTTP request
  if HTTP.HTTPMethod('GET', URL) then
  begin
    // If its a 301 or 302 we need to do more processing
    if (HTTP.ResultCode = 301) or (HTTP.ResultCode = 302) then
    begin
      // Check the headers for the Location header
      for i := 0 to HTTP.Headers.Count -1 do
      begin
        // Extract the URL
        if Copy(HTTP.Headers[i], 1, 8) = 'Location' then
          realurl := Copy(HTTP.Headers[i], 11, Length(HTTP.Headers[i]) - 11);
      end;
      writeln('Redirecting to ', realurl);
      // If we have a URL, run it through the same function
      if Length(realurl) > 1 then l.Text := HTTPGet(realurl, UserAgent);
    end
    else l.LoadFromStream(Http.Document);
  end;
  // Return result
  Result := l.Text;
  // Clean up
  HTTP.Free;
  l.Free;
end;

procedure main;
var
  response: String;
  url: String;
begin
  url := 'http://matthewhipkin.co.uk';
  writeln('Checking ', url);
  response := HTTPGet(url, 'Mozilla/5.0 (X11; FreeBSD amd64; rv:50.0) Gecko/20100101 Firefox/50.0');
  //writeln(response);
end;

begin
  main;
end.

Tested with FreePascal 3.0.0 but should work fine on Delphi.

blog comments powered by Disqus