[Winhttp]_[C/C++]_[win 32 SDKを使用したWindows HTTP Services(WinHTTP)エージェントによるWebページのダウンロード]


シーン:
1.win 32 SDKを使用するとコンパイルされたプログラムはサードパーティ製ライブラリよりも小さく制御しやすい.
2.欠点はプラットフォームにまたがることができなくて、linuxの上でまた1セットの実現を書き直す必要があります.
3.利点はwin 32 SDKの使用をより熟知できることです.
プログラムはあまり整理されていないので、時間があればまたやります.
// test_http.cpp :              。
//

#include <stdio.h>

#include "windows.h"
#include "Winhttp.h"

void WinDownload()
{
  DWORD dwSize = 0;
  DWORD dwDownloaded = 0;
  LPSTR pszOutBuffer;
  BOOL  bResults = FALSE;
  HINTERNET  hSession = NULL, 
             hConnect = NULL,
             hRequest = NULL;

  // Use WinHttpOpen to obtain a session handle.
  hSession = WinHttpOpen( L"WinHTTP Example/1.0",  
                          WINHTTP_ACCESS_TYPE_NAMED_PROXY,
                          L"192.168.0.1:808", 
                          L"192.168.0.1:808", 0 );

  //hSession = WinHttpOpen( L"WinHTTP Example/1.0",  
  //                        WINHTTP_ACCESS_TYPE_NO_PROXY,
  //                        WINHTTP_NO_PROXY_NAME, 
  //                        WINHTTP_NO_PROXY_BYPASS, 0 );
  
  // Specify an HTTP server.
  if( hSession )
    hConnect = WinHttpConnect( hSession, L"www.w3school.com.cn",
                               INTERNET_DEFAULT_HTTP_PORT, 0 );
  // Create an HTTP request handle.
  if( hConnect )
    hRequest = WinHttpOpenRequest( hConnect, L"GET", L"/example/xmle/note.xml",
                                   NULL, WINHTTP_NO_REFERER, 
                                   WINHTTP_DEFAULT_ACCEPT_TYPES, 
                                   WINHTTP_FLAG_REFRESH );

  // Send a request.
  if( hRequest )
    bResults = WinHttpSendRequest( hRequest,
                                   WINHTTP_NO_ADDITIONAL_HEADERS, 0,
                                   WINHTTP_NO_REQUEST_DATA, 0, 
                                   0, 0 );


  // End the request.
  if( bResults )
    bResults = WinHttpReceiveResponse( hRequest, NULL );
  
  // Keep checking for data until there is nothing left.
  if( bResults )
  {
    do 
    {
      // Check for available data.
      dwSize = 0;
      if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
        printf( "Error %u in WinHttpQueryDataAvailable.
", GetLastError( ) ); // Allocate space for the buffer. pszOutBuffer = new char[dwSize+1]; if( !pszOutBuffer ) { printf( "Out of memory
" ); dwSize=0; } else { // Read the data. ZeroMemory( pszOutBuffer, dwSize+1 ); if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded ) ) printf( "Error %u in WinHttpReadData.
", GetLastError( ) ); else printf( "%s", pszOutBuffer ); // Free the memory allocated to the buffer. delete [] pszOutBuffer; } } while( dwSize > 0 ); } // Report any errors. if( !bResults ) printf( "Error %d has occurred.
", GetLastError( ) ); // Close any open handles. if( hRequest ) WinHttpCloseHandle( hRequest ); if( hConnect ) WinHttpCloseHandle( hConnect ); if( hSession ) WinHttpCloseHandle( hSession ); } int main(int argc, char* argv[]) { WinDownload(); return 0; }