如何使用C++在線獲取文件內容?.NET WebClient.DownloadData(url)在C++/WinAPI中的替代?
0
A
回答
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
使用以下功能。
WinHttpConnect
WinHttpOpenRequest
WinHttpSendRequest
WinHttpReceiveResponse
WinHttpQueryDataAvailable
WinHttpReadData
相關問題
- 1. 替代在.NET
- 2. WebClient.DownloadData從
- 3. com +在.net中的替代方案?
- 4. 在ASP .NET中的替代重定向
- 5. ZooKeeper替代.net
- 6. .NET替代
- 7. .NET/WPF替代
- 8. GET的替代語法在url中
- 9. WebClient.DownloadData掛起
- 10. 在webClient.DownloadData上設置超時?
- 11. .Net MVC替代Formtastic
- 12. .NET的替代品提供了關於uris和url的apis
- 13. .NET 3.5中的GetGlobalAsaxType的替代方法?
- 14. 替代.NET的Uri實現?
- 15. 替代.NET的客戶端
- 16. 使用WebClient.BaseAddress替代Silverlight中的基礎URL替代方案
- 17. .NET Core中的SignedCms替代方案
- 18. 在URL中替換URL中的空格#
- 19. .NET 4.0替代.NET 4.5命名空間
- 20. .NET 2/VB:RequestValidation =假替代
- 21. .NET WinForms ToolStrip替代方案
- 22. 是否有.Net替代GetAsyncKeyState?
- 23. .net替代玻璃魚
- 24. 在PHP中的URL替換
- 25. 替換/在Javascript中的URL
- 26. .NET會話替代在全球範圍
- 27. 什麼是.net中的Applet替代品.net
- 28. 用變量代替URL
- 29. 用戶代理在.jsp中的替代
- 30. WebClient.DownloadData()返回0字節
謝謝你的一個很好的答案! – Alex 2011-04-09 13:35:54