We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Geting file size using wininet?

nikola_mk
nikola_mk asked
on
Medium Priority
1,654 Views
Last Modified: 2008-01-09
Hi I use wininet library for downloading file from net.I use this function for getting file size, but this function not work properly don't give me results(return 0) for any URL (valid URL)       especially on bigger files.What is problem with bigger files??or how to detect redirect?
nn ex.
http://download2.gamespot.com/d4/gsc/action/fearcombat/fearcombat_en_107.exe (return 0)

http://us.rd.yahoo.com/games/buzz/downloads/486514/SIG=1344l74qj/*http%3A//h.yimg.com/download2.games.yahoo.com/games/buzz2/
content/p/0/486514/paraworld_sp_demo.exe (return 1.3GB)


Please give me some idea or function for this

function TMainForm.GetResourceSize(const AURL: string): Integer;
var
  hOpen, hConnect, hResource: HINTERNET;
  host, resource: string;
  buflen, tmp: Cardinal;
begin
  ParseURL(AURL, host, resource);

  hOpen := InternetOpen('WinInet resuming sample', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if  Assigned(hOpen) then edtFile.Text:=edtFile.Text+' 1 OK ' else edtFile.Text:=edtFile.Text+' 1 NO ';
  hConnect := InternetConnect(hOpen, PChar(host), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
  if  Assigned(hConnect) then edtFile.Text:=edtFile.Text+' 2 OK '  else  edtFile.Text:=edtFile.Text+' 2 NO ';
  hResource := HttpOpenRequest(hConnect, 'HEAD', PChar(resource), nil, nil, nil, 0, 0);
  if  Assigned(hResource) then edtFile.Text:=edtFile.Text+' 3 OK ' else  edtFile.Text:=edtFile.Text+' 3 NO ';

    HttpSendRequest(hResource, nil, 0, nil, 0);

  buflen := SizeOf(Result);
  tmp := 0;
  Result := 0;
  HttpQueryInfo(hResource, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER,
    @Result, buflen, tmp);

  InternetCloseHandle(hConnect);
  InternetCloseHandle(hOpen);
end;



Regards, Nikola
Comment
Watch Question

CERTIFIED EXPERT
Commented:
The reason the first url in your example returns zero is because there is an uncaught error due to a redirection taking place. The following example should illustrate some error trapping and handling of the redirection.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, SysConst, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Wininet, StdCtrls;

type
  EWinInetError = class(Exception)
  public
    ErrorCode: DWORD;
  end;

  TForm1 = class(TForm)
    Edit1: TEdit;
    Label1: TLabel;
    Button1: TButton;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    function GetResourceSize(const AURL: string): Integer;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure RaiseLastWinInetError;
var LastError, len: cardinal;
    Error: EWinInetError;
    hM: HMODULE;
    errMsg: string;
begin
  LastError := GetLastError;
  hm:= GetModuleHandle(pchar('wininet.dll'));
  SetLength(errMsg, 257);
  len:= FormatMessage(FORMAT_MESSAGE_FROM_HMODULE, pointer(hM), LastError, 0, @ErrMsg[1], 256, nil);
  SetLength(errMsg, len);
  if len > 0
    then Error:= EWinInetError.Create(Format('WinInet error: %d'#13'%s', [LastError, ErrMsg]))
    else begin
      if (LastError >= INTERNET_ERROR_BASE) AND (LastError <= INTERNET_ERROR_LAST)
        then Error:= EWinInetError.Create(Format('Unknown WinInet error: %d', [LastError]))
        else Error := EWinInetError.CreateResFmt(@SOSError, [LastError, SysErrorMessage(LastError)]);
    end;
  Error.ErrorCode:= LastError;
  raise Error;
end;

procedure ParseURL(URL: String; var HostName, FileName: String);
var i: Integer;
begin
  if Pos('http://', LowerCase(URL)) <> 0
    then System.Delete(URL, 1, 7);

  if Pos('https://', LowerCase(URL)) <> 0
    then System.Delete(URL, 1, 8);

  i := Pos('/', URL);
  HostName := Copy(URL, 1, i);
  FileName := Copy(URL, i, Length(URL) - i + 1);

  if (Length(HostName) > 0) and (HostName[Length(HostName)] = '/')
    then SetLength(HostName, Length(HostName) - 1);
end;


function GetINTERNET_OPTION_URL(InternetHandle: HINTERNET): string;
var len: cardinal;
begin
  len:= 0;
  result:= '';
  InternetQueryOption(InternetHandle, INTERNET_OPTION_URL, pchar(result), len);
  if len > 0 then
  begin
    SetLength(result, len);
    if not InternetQueryOption(InternetHandle, INTERNET_OPTION_URL,
                               pchar(result), len)
      then RaiseLastWinInetError;
    SetLength(result, len);
  end;
end;

function TForm1.GetResourceSize(const AURL: string): Integer;
var
  hOpen, hConnect, hResource: HINTERNET;
  host, resource, RetURL: string;
  buflen, tmp: Cardinal;
begin
  result:= -1;
  ParseURL(AURL, host, resource);

  hOpen := InternetOpen(pchar('WinInet resuming sample'), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if NOT Assigned(hOpen) then RaiseLastWinInetError;
  try
    hConnect := InternetConnect(hOpen, PChar(host),
                                INTERNET_DEFAULT_HTTP_PORT,
                                nil, nil,
                                INTERNET_SERVICE_HTTP,
                                0, 0);
    if not assigned(hConnect) then RaiseLastWinInetError;
    try
      hResource := HttpOpenRequest(hConnect, pchar('HEAD'), PChar(resource),
                                   nil, nil, nil,
                                   0,
                                   0);
      if not assigned(hResource) then RaiseLastWinInetError;
      try

        try
          if NOT HttpSendRequest(hResource, nil, 0, nil, 0)
            then RaiseLastWinInetError;
        except on e: EWinInetError do
          case e.ErrorCode of
            ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR,
            ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR:
              begin
                RetURL:= GetINTERNET_OPTION_URL(hResource);
                if MessageDlg('Url was redirected to: '+RetUrl+
                              sLineBreak+sLineBreak+'Continue?',
                              mtWarning, [mbOK, mbCancel], 0)
                  = mrOK
                  then result:= GetResourceSize(RetUrl);
                Exit;
              end;
            else raise e;
          end;
        end;

        buflen := SizeOf(Result);
        tmp := 0;
        Result := 0;
        if not HttpQueryInfo(hResource, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER,
                             @Result, buflen, tmp)
          then RaiseLastWinInetError;
      finally
        InternetCloseHandle(hResource);
      end;
    finally
      InternetCloseHandle(hConnect);
    end;
  finally
    InternetCloseHandle(hOpen);
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
var sz: integer;
begin
  sz:= GetResourceSize(Edit1.Text);
  Label2.Caption:= format('Size: %d', [sz]);
end;

end.


Kind regards
Pierre

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.