WinInet 利用プログラミング(1) | 今宵は月が高い。注意されたし。

WinInet 利用プログラミング(1)

大したコードじゃないんですが、WinINet ユニットを使ってインターネット上からファイルを読み込む関数。

function LoadFromInternet( URL:String; Document:TStrings ): Boolean;
const
  BufSize = 1000;
var
  hINet: HINTERNET;
  hURL : HINTERNET;
  iRead: Cardinal;
  pBuf : PChar;
  bRslt: Boolean;
  Wrk : String;
begin
  Result := False;
  Document.Clear;

  hINet := wininet.InternetOpen( gcSenderString, INTERNET_OPEN_TYPE_PRECONFIG, NIL, NIL, 0 );
  if not Assigned(hINet) then Exit;
  
  hURL := wininet.InternetOpenUrl( hINet, PChar(URL), NIL, 0, INTERNET_FLAG_RELOAD, 0 );
  if not Assigned(hURL) then
  begin
    wininet.InternetCloseHandle( hINet );
    Exit;
  end;


  try
    iRead := BufSize;
    pBuf := StrAlloc( iRead );
    Wrk := '';
    repeat
      bRslt := InternetReadFile( hURL, pBuf, BufSize, iRead );
      if bRslt and (iRead > 0) then
        Wrk := Wrk +Copy( pBuf, 1, iRead );
    until (bRslt = False) or (iRead = 0);
    if (Wrk <> '') then Document.Text := Wrk;

  finally  
    StrDispose( pBuf ) ;
    wininet.InternetCloseHandle( hURL );
    wininet.InternetCloseHandle( hINet );
  end;

  Result := (Document.Text <> '')
end;