C++ Builder Tips


webサーバからhtmlを取得する


WinInetの機能を利用して、webサーバからhtmlを取得します。
Inet.libをプロジェクトに追加します。C++BuilderのLib のフォルダ内にあります。

結果はhtmlというAnsiString型のなかにhtmlファイルの内容がよみこまれているはずです。

#include <wininet.h>

AnsiString html = "";
AnsiString Url ="http://www.yahoo.com";

HINTERNET hSession;
hSession = InternetOpen( "MyApp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0 );
if( hSession )
{
  HINTERNET hService;
  hService = InternetOpenUrl( hSession, Url.c_str(), NULL, 0, 0, 0 );
  if(hService)
  {
    while(1)
    {
      char lpBuffer[1024+1]; //一度に読み込むバイト数
      DWORD dwBytesRead;     //読み込んだbyte数
      InternetReadFile(hService, lpBuffer, 1024, &dwBytesRead);
      if(dwBytesRead == 0) break; //読み込んだbyte数が0になったらループを抜ける
      lpBuffer[dwBytesRead] = 0; //読み込んだデータの最後に0を書き込み文字列化
      html += lpBuffer; //htmlに追加
    }
  }
  InternetCloseHandle(hService);
}
InternetCloseHandle(hSession);



目次に戻る
Copyright(c) 2008 WoodenSoldier Software