2011-03-30 59 views

回答

2

有很多方法可以做到這一點。

的WinInet

首先Windows有一個內置的API允許你發出HTTP請求,這是相當簡單易用。我用這個簡單的包裝類用它來下載文件:

/** 
* Simple wrapper around the WinInet library. 
*/ 
class Inet 
{ 
public: 
    explicit Inet() : m_hInet(NULL), m_hConnection(NULL) 
    { 
     m_hInet = ::InternetOpen(
      "My User Agent", 
      INTERNET_OPEN_TYPE_PRECONFIG, 
      NULL, 
      NULL, 
      /*INTERNET_FLAG_ASYNC*/0); 
    } 

    ~Inet() 
    { 
     Close(); 

     if (m_hInet) 
     { 
      ::InternetCloseHandle(m_hInet); 
      m_hInet = NULL; 
     } 
    } 

    /** 
    * Attempt to open a URL for reading. 
    * @return false if we don't have a valid internet connection, the url is null, or we fail to open the url, true otherwise. 
    */ 
    bool Open(LPCTSTR url) 
    { 
     if (m_hInet == NULL) 
     { 
      return false; 
     } 

     if (url == NULL) 
     { 
      return false; 
     } 

     m_hConnection = ::InternetOpenUrl(
      m_hInet, 
      url, 
      NULL /*headers*/, 
      0 /*headers length*/, 
      INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI, 
      reinterpret_cast<DWORD_PTR>(this)); 

     return m_hConnection != NULL; 
    } 

    /** 
    * Read from a connection opened with Open. 
    * @return true if we read data. 
    */ 
    bool ReadFile(LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD dwRead) 
    { 
     ASSERT(m_hConnection != NULL); 

     return ::InternetReadFile(m_hConnection, lpBuffer, dwNumberOfBytesToRead, dwRead) != 0; 
    } 

    /** 
    * Close any open connection. 
    */ 
    void Close() 
    { 
     if (m_hConnection != NULL) 
     { 
      ::InternetCloseHandle(m_hConnection); 
      m_hConnection = NULL; 
     } 
    } 

private: 
    HINTERNET m_hInet; 
    HINTERNET m_hConnection; 
}; 

的這種用法很簡單:

Inet inet; 
if (inet.Open(url)) 
{ 
    BYTE buffer[UPDATE_BUFFER_SIZE]; 
    DWORD dwRead; 
    while (inet.ReadFile(&buffer[0], UPDATE_BUFFER_SIZE, &dwRead)) 
    { 
     // TODO: Do Something With buffer here 
     if (dwRead == 0) 
     { 
      break; 
     } 
    } 
} 

的libcurl

如果你寧願避免特定於Windows的API那麼你可能會比使用libcurl庫來獲取使用各種協議(包括HTTP)的文件差很多。有一個很好的示例顯示如何直接將URL檢索到內存中(避免下載到磁盤):getinmemory sample

+0

謝謝你的一個很好的答案! – Alex 2011-04-09 13:35:54

0

使用以下功能。

WinHttpConnect 
WinHttpOpenRequest 
WinHttpSendRequest 
WinHttpReceiveResponse 
WinHttpQueryDataAvailable 
WinHttpReadData