Downloading any URL using default network configuration (Views: 100)


How do I access files through a proxy? How can I use cached files downloads?


Starting with Internet Explorer 3, Microsoft provides a very useful API, Wininet. It contains the core functionality of IE. When you use those functions, you automatically benefit from features of IE, such as Proxy configuration, file Caching, etc.

Here is a demonstration of using those functions to download a file using it's URL. It can be any valid URL, ftp://, http://, gopher://, etc.

Consult the Win32 Internet API Functions reference on MSDN online for more information.

function DownloadFile(const Url: string): string;
  NetHandle: HINTERNET;
  UrlHandle: HINTERNET;
  Buffer: array[0..1024] of char;
  BytesRead: cardinal;
  Result := '';
  NetHandle := InternetOpen('Delphi 5.x', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);

  if Assigned(NetHandle) then

    UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD,

    if Assigned(UrlHandle) then
      { UrlHandle valid? Proceed with download }
      FillChar(Buffer, SizeOf(Buffer), 0);
        Result := Result + Buffer;
        FillChar(Buffer, SizeOf(Buffer), 0);
        InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
      until BytesRead = 0;
      { UrlHandle is not valid. Raise an exception. }
      raise Exception.CreateFmt('Cannot open URL %s', [Url]);

    { NetHandle is not valid. Raise an exception }
    raise Exception.Create('Unable to initialize Wininet');

<< Back to main page