使用 InternetReadFile 来获取文件

来源:互联网 发布:淘宝子账号 阿里妈妈 编辑:程序博客网 时间:2024/05/17 08:26

<script type="text/javascript"><!--google_ad_client = "pub-0241434510974184";/* 博客文章广告728x90, */google_ad_slot = "7316585398";google_ad_width = 728;google_ad_height = 90;// --></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

概要

使用 WinInet API, InternetReadFile 返回下列缓冲区:
<body> <h1> 未找到 HTTP/1.0 406HTTP 否接受对象 </h1> </body>

更多信息

这是 HTTP 服务器特定错误。 MicrosoftIIS 当没有正确接受头时可能返回该错误: * 接受 " / * ") (HTTP 请求中。 可以以下列来添加这些标头:
   InternetOpenUrl(),   HttpSendRequest(),   HttpAddRequestHeaders()
注意, 其他 HTTP 服务器可能或不以相同方式行为。 以下代码演示了如何传输任何类型的文件与 WinInet API:
   BOOL GetFile (HINTERNET IN hOpen, // Handle from InternetOpen()                 CHAR *szUrl,        // Full URL                 CHAR *szFileName)   // Local file name   {       DWORD dwSize;       CHAR   szHead[] = "Accept: */*/r/n/r/n";       VOID * szTemp[25];       HINTERNET  hConnect;      FILE * pFile;       if ( !(hConnect = InternetOpenUrl ( hOpen, szUrl, szHead,             lstrlen (szHead), INTERNET_FLAG_DONT_CACHE, 0)))       {         cerr << "Error !" << endl;           return 0;       }       if  ( !(pFile = fopen (szFileName, "wb" ) ) )      {           cerr << "Error !" << endl;          return FALSE;      }       do       {          // Keep coping in 25 bytes chunks, while file has any data left.          // Note: bigger buffer will greatly improve performance.          if (!InternetReadFile (hConnect, szTemp, 50,  &dwSize) )          {              fclose (pFile);             cerr << "Error !" << endl;            return FALSE;          }          if (!dwSize)              break;  // Condition of dwSize=0 indicate EOF. Stop.          else             fwrite(szTemp, sizeof (char), dwSize , pFile);       }   // do      while (TRUE);      fflush (pFile);      fclose (pFile);      return TRUE;   }
相同任务可完成与 WinInet MFC 类: 以下列方式
   #include <afx.h>   #include <afxinet.h>   BOOL  GetFile (CHAR *szUrl, CHAR *szFileName)   {   TCHAR sz[1024];   CInternetSession session (_T("MyTest agent"), 1,     INTERNET_OPEN_TYPE_DIRECT);   CStdioFile* pFile = NULL;   CHAR   szHead[] = "Accept: */*/r/n/r/n";       DWORD nRead;   CFile myFile;   CFileException fileException;   if ( !myFile.Open (szFileName, CFile::modeCreate | CFile::modeReadWrite,      &fileException ) )   {   cerr << "Can't open file: " << szFileName    << " error = " << fileException.m_cause  <<"/n";   return FALSE;   }   try   {   pFile = session.OpenURL (szUrl, 1, INTERNET_FLAG_RELOAD   |INTERNET_FLAG_TRANSFER_BINARY,    szHead, -1L);   }   catch (CInternetException *pEx)   {   cerr <<"OpenUrl failed: "<< pEx-> m_dwError << endl;   return FALSE;   }       do   {   nRead = pFile->Read(sz, 1023);   if (nRead != 0)   myFile.Write (sz, nRead);   }   while (nRead != 0);   myFile.Close();   pFile->Close();   if (pFile != NULL)   delete pFile;   session.Close();   return TRUE;   }