如何在C/C++中使用WinHTTP下载文件?

前端之家收集整理的这篇文章主要介绍了如何在C/C++中使用WinHTTP下载文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道如何下载html / txt页面.例如 :
  1. //Variables
  2. DWORD dwSize = 0;
  3. DWORD dwDownloaded = 0;
  4. LPSTR pszOutBuffer;
  5. vector <string> vFileContent;
  6. BOOL bResults = FALSE;
  7. HINTERNET hSession = NULL,hConnect = NULL,hRequest = NULL;
  8.  
  9. // Use WinHttpOpen to obtain a session handle.
  10. hSession = WinHttpOpen( L"WinHTTP Example/1.0",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);
  11.  
  12. // Specify an HTTP server.
  13. if (hSession)
  14. hConnect = WinHttpConnect( hSession,L"nytimes.com",INTERNET_DEFAULT_HTTP_PORT,0);
  15.  
  16. // Create an HTTP request handle.
  17. if (hConnect)
  18. hRequest = WinHttpOpenRequest( hConnect,L"GET",L"/ref/multimedia/podcasts.html",NULL,WINHTTP_NO_REFERER,NULL);
  19.  
  20. // Send a request.
  21. if (hRequest)
  22. bResults = WinHttpSendRequest( hRequest,WINHTTP_NO_ADDITIONAL_HEADERS,WINHTTP_NO_REQUEST_DATA,0);
  23.  
  24.  
  25. // End the request.
  26. if (bResults)
  27. bResults = WinHttpReceiveResponse( hRequest,NULL);
  28.  
  29. // Keep checking for data until there is nothing left.
  30. if (bResults)
  31. do
  32. {
  33.  
  34. // Check for available data.
  35. dwSize = 0;
  36. if (!WinHttpQueryDataAvailable( hRequest,&dwSize))
  37. printf( "Error %u in WinHttpQueryDataAvailable.\n",GetLastError());
  38.  
  39. // Allocate space for the buffer.
  40. pszOutBuffer = new char[dwSize+1];
  41. if (!pszOutBuffer)
  42. {
  43. printf("Out of memory\n");
  44. dwSize=0;
  45. }
  46. else
  47. {
  48. // Read the Data.
  49. ZeroMemory(pszOutBuffer,dwSize+1);
  50.  
  51. if (!WinHttpReadData( hRequest,(LPVOID)pszOutBuffer,dwSize,&dwDownloaded))
  52. {
  53. printf( "Error %u in WinHttpReadData.\n",GetLastError());
  54. }
  55. else
  56. {
  57. printf("%s",pszOutBuffer);
  58. // Data in vFileContent
  59. vFileContent.push_back(pszOutBuffer);
  60. }
  61.  
  62. // Free the memory allocated to the buffer.
  63. delete [] pszOutBuffer;
  64. }
  65.  
  66. } while (dwSize>0);
  67.  
  68.  
  69. // Report any errors.
  70. if (!bResults)
  71. printf("Error %d has occurred.\n",GetLastError());
  72.  
  73. // Close any open handles.
  74. if (hRequest) WinHttpCloseHandle(hRequest);
  75. if (hConnect) WinHttpCloseHandle(hConnect);
  76. if (hSession) WinHttpCloseHandle(hSession);
  77.  
  78. // Write vFileContent to file
  79. ofstream out("test.txt",ios::binary);
  80. for (int i = 0; i < (int) vFileContent.size();i++)
  81. out << vFileContent[i];
  82. out.close();

当我尝试下载图片时,我只得到文件的第一行,没有错误信息.问题似乎与WinHttpOpenRequest函数中的此参数(ppwszAcceptTypes)有关.

link text

解决方法

猜你在找的C&C++相关文章