2011-03-30 1 views

답변

2

이렇게하는 방법에는 여러 가지가 있습니다.

WinInet을

우선 윈도우가 내장되어 API 사용하는 것이 합리적으로 간단 HTTP 요청을 만들 수 있도록.

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를 피하려는 경우 :

/** 
* 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; 
}; 

이의 사용법은 매우 간단하다 : 나는 그것을 사용하여 파일을 다운로드하려면이 간단한 래퍼 클래스를 사용 그러면 libcurl 라이브러리를 사용하여 HTTP를 비롯한 다양한 프로토콜을 사용하여 파일을 가져 오는 것보다 훨씬 어려울 수 있습니다. URL을 메모리로 직접 가져 오는 방법을 보여주는 좋은 예가 있습니다 (디스크로 다운로드하는 것을 피하십시오) : getinmemory sample.

+0

대단히 감사합니다! – Alex

0

다음 기능을 사용하십시오.

WinHttpConnect 
WinHttpOpenRequest 
WinHttpSendRequest 
WinHttpReceiveResponse 
WinHttpQueryDataAvailable 
WinHttpReadData