Solved

Geting file size using wininet?

Posted on 2006-11-02
1
1,467 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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Delphi 2 59
how can i search if string exist in array ? 3 55
Graphics32 under Delphi 10.1 Berlin 2 60
Not able to call Delphi XE10 dll function from Delphi 6.0 4 26
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
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…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

785 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