Mirror

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


Problem/Question/Abstract:

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

Answer:

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;
var
  NetHandle: HINTERNET;
  UrlHandle: HINTERNET;
  Buffer: array[0..1024] of char;
  BytesRead: cardinal;
begin
  Result := '';
  NetHandle := InternetOpen('Delphi 5.x', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);

  if Assigned(NetHandle) then
  begin

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

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

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

<< Back to main page