Solved

Geting file size using wininet?

Posted on 2006-11-02
1
1,448 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
0
Comment
Question by:nikola_mk
1 Comment
 
LVL 14

Accepted Solution

by:
Pierre Cornelius earned 200 total points
ID: 17861511
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
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
Hello everybody This Article will show you how to validate number with TEdit control, What's the TEdit control? TEdit is a standard Windows edit control on a form, it allows to user to write, read and copy/paste single line of text. Usua…
This video discusses moving either the default database or any database to a new volume.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now