Page 1 of 1

Lazarus – Windows – How to download a file from the web (HTTPS) without OpenSSL

Lazarus – Windows – How to download a file from the web (HTTPS) without OpenSSL

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
Examples: "MacOS X - Your question", "MS Word - Your Tip or Trick".

Please note that switching to another language when reading a post will not work!
Posts will not have a translated counterpart.




RSS Feed

Home Forums Software Development Delphi, Lazarus, Free Pascal Lazarus – Windows – How to download a file from the web (HTTPS) without OpenSSL

Viewing 1 post (of 1 total)
  • Author
    Posts
  • 13065

    Hans
    Keymaster

    Sometimes we need a quick and easy way to download a file from the Internet, and these days HTTPS is the way to go.
    Unfortunately, most tools for Lazarus require OpenSSL (Indy, Synapse, etc), which means you’d have to distribute OpenSSL DLL’s with your application, something I’d like to avoid for simple downloads.

    The fix is using Windows Internet (WinINet) application programming interface (API), with the following code using the wininet unit (source):

    Uses ... wininet ...
    
    ... function GetWebPage(const Url: string): string;
    var
      NetHandle: HINTERNET;
      UrlHandle: HINTERNET;
      Buffer: array[0..1023] of Byte;
      BytesRead: dWord;
      StrBuffer: UTF8String;
    begin
      Result := '';
      BytesRead := Default(dWord);
      NetHandle := InternetOpen('Mozilla/5.0(compatible; WinInet)', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
     
      // NetHandle valid?
      if Assigned(NetHandle) then
        Try
          UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0);
     
          // UrlHandle valid?
          if Assigned(UrlHandle) then
            Try
              repeat
                InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
                SetString(StrBuffer, PAnsiChar(@Buffer[0]), BytesRead);
                Result := Result + StrBuffer;
              until BytesRead = 0;
            Finally
              InternetCloseHandle(UrlHandle);
            end
          // o/w UrlHandle invalid
          else
            ShowMessage('Cannot open URL: ' + Url);
        Finally
          InternetCloseHandle(NetHandle);
        end
      // NetHandle invalid
      else
        raise Exception.Create('Unable to initialize WinInet');
    end;
    {$ENDIF} 
Viewing 1 post (of 1 total)



You must be logged in to reply to this topic.