Opening URLs

File: JVE.OpenURL.pas Inheritance: TComponent ⬅ TJVEOpenURL

This component opens the default app, associated with the scheme on the platform (i.e. “http://” will open a browser; “ftp://” will open an FTP client and a custom scheme will be opened by the app, defined as supporting it.

This component defines a single property URL (an address to open), no events and the following instance methods:

  • Open – opens the URL; returns True, if successfully opened.
  • CanOpen – checks whether the URL can be opened (i.e. scheme is supported).

In addition to this, it provides the following class methods:

  • OpenURL(URL) and CanOpenURL(URL) – convenience: as above, but without creating a component.
  • SchemeSupported(Scheme) – checks whether the scheme is (i.e. “http”, “ftp”, etc.) is supported by the system and can be opened.
  • URLEncode(Value) – convenience function: encodes the string to make it safe for URL inclusion (i.e. “Set to 40%” will become “Set%20to%2040%25”).

When working with this class, you should always use the full URL, including the scheme (otherwise it might fail on some platforms and the defaults used might not be consistent).

 

Special class methods are also provided in this component, providing an easy way to easily download the content of the provided URL (these function should only be used with HTTP and HTTPS protocols).

These functions download the content directly into a memory stream or a bitmap, making them easy to use, but they should not be used on large files. The function blocks the calling thread until they finish, so calling it on a secondary thread is recommended.

The functions are defined as follows (several overloads are given to achieve this):

  • DownloadURL(URL: String[, Headers: TStrings][, var Error: String]): TMemoryStream;
  • DownloadBitmap(URL:String[,Headers: TStrings][,var Error: String]): TBitmap;

The function returns the filled memory stream, bitmap or nil, if an error occurred. An optional error parameter provides a user readable message; optionally extra HTTP headers can be provided as well.

If planning to use these functions on multiple platforms, it is important to free the resulting class after assigning the value. Notice, due to a bug in Delphi, DownloadBitmap synchronizes with the main thread to decode the image (if the main thread is stuck, this call will also stuck).

 

These functions use appropriate OS functions, instead of trying to support download itself or using the Indy library. As such it also allows for SSL connectivity without using additional encryption libraries on all platforms.