[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Geting file size using wininet?

Posted on 2006-11-02
1
Medium Priority
?
1,549 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

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…
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…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Suggested Courses

649 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