?
Solved

Geting file size using wininet?

Posted on 2006-11-02
1
Medium Priority
?
1,525 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 14

Accepted Solution

by:
Pierre Cornelius earned 800 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

800 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