C++ WinInet API 斷點續傳

來源:互聯網
上載者:User

標頭檔:

#pragma  once  #include <string>  using namespace std;  // 多位元組轉寬位元組 extern wstring StrToWstring(string strsrc);   // 寬位元組轉多位元組 extern string WstrToString(wstring strsrc);   // 字串轉整形 extern int  StrToInt(string strsrc);  // 整形轉字串 extern string IntToString(int nValue);  // 擷取目前時間 extern const char* GetCurrentSystimetime();  // 擷取當前系統零檔案目錄 extern const char* GetCurrentSysTempPath();  // 擷取當前可可執行程式檔案路徑 extern string GetCurrentExePath();  // 識別碼轉String extern string IdToString( unsigned int nID);  // 提取出檔案名稱字 根據完全路徑提取出檔案名稱字 extern string GetFileName(string strsrc);  // 錯誤打應 extern void ErrorExit(); 

cpp檔案 :

// #include "stdafx.h"      #include "Utility.h"   #include <Windows.h>   #include <time.h>          wstring StrToWstring(string strsrc)   {       long size   =   MultiByteToWideChar(CP_ACP,0,strsrc.c_str(),-1,NULL,0);       if(size<1)           return L"";       wchar_t * wText = new wchar_t[size + 2];       if(!wText)           return L"";       MultiByteToWideChar(CP_ACP,0,strsrc.c_str(),-1,wText,size+2);       //      wchar_t wstate[256];   //  MultiByteToWideChar( CP_ACP, 0, state.data(), -1, wstate, 256);          wstring wstr = wText;       delete [] wText;         return wstr;   }      string WstrToString(wstring strsrc)   {       char buf[512];           ::WideCharToMultiByte(CP_ACP, 0, strsrc.c_str(), -1, buf, sizeof buf , NULL, NULL);       return buf;   }         int StrToInt(string strsrc)   {      return atoi(strsrc.c_str());   }      string IntToString(int nValue)   {       char mbzTemp[256];       itoa(nValue,mbzTemp,10);//按10進位轉換       return string(mbzTemp);   }      const char* GetCurrentSystimetime()   {       static string t_strtemptime;       struct tm *newtime;       time_t long_time;       time( &long_time );                 newtime = localtime( &long_time );        char  mbzTemp[512];       ::ZeroMemory(mbzTemp,sizeof(mbzTemp));          if(NULL == newtime)       {           t_strtemptime="TimeIsErr";           return t_strtemptime.c_str();       }       sprintf(mbzTemp,"%d-%d-%d %d-%d-%d",           newtime->tm_year+1900,newtime->tm_mon+1,newtime->tm_mday,           newtime->tm_hour,newtime->tm_min,newtime->tm_sec);          t_strtemptime = mbzTemp;       return t_strtemptime.c_str();   }      // 擷取當前系統零檔案目錄   const char* GetCurrentSysTempPath()   {       static char szTempPath[512];       ZeroMemory(szTempPath,sizeof(szTempPath));       GetTempPathA(sizeof(szTempPath),szTempPath);       return szTempPath;   }         // 擷取當前可可執行程式檔案路徑   string GetCurrentExePath()   {       static char szTempPath[512];       ZeroMemory(szTempPath,sizeof(szTempPath));       ::GetModuleFileNameA(NULL,szTempPath,sizeof(szTempPath));       string strtemp = szTempPath;       strtemp = strtemp.substr(0,strtemp.rfind('\\')+1);      return strtemp;   }      // 識別碼轉String   string IdToString( unsigned int nID)   {     static char szTempBuff[1024];     LoadString(NULL,nID,szTempBuff,sizeof(szTempBuff));     return szTempBuff;   }      // 提取出檔案名稱字 根據完全路徑提取出檔案名稱字   string GetFileName(string strsrc)   {       string str = strsrc.substr(strsrc.rfind('//')+1,strsrc.length()-1);       return str;   }      void ErrorExit()    {        TCHAR szBuf[80];        LPVOID lpMsgBuf;       DWORD dw = GetLastError();           FormatMessage(           FORMAT_MESSAGE_ALLOCATE_BUFFER |            FORMAT_MESSAGE_FROM_SYSTEM,           NULL,           dw,           MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),           (LPTSTR) &lpMsgBuf,           0, NULL );          wsprintf(szBuf,            "錯誤 failed with error %d: %s", dw, lpMsgBuf);           MessageBox(NULL, szBuf, "Error", MB_OK);           LocalFree(lpMsgBuf);       ExitProcess(dw);    }  

調用方法:

#include <Windows.h>   #include <wininet.h>   #include <stdio.h>   #include <string>   #include <iostream>   #include "Utility.h"      using namespace std;      #pragma comment(lib, "wininet.lib")      #define URL_STRING_TEST    "http://eng.edu-edu.com.cn/audio/Onelove.mp3"      void main()   {       URL_COMPONENTS crackedURL;       TCHAR  szBuffer[1024];//這裡是下載緩衝區大小 1KB大小緩衝寫入一次       TCHAR szHostName[128];       TCHAR szUrlPath[256];       ZeroMemory(&crackedURL, sizeof (URL_COMPONENTS));       crackedURL.dwStructSize     = sizeof (URL_COMPONENTS);       crackedURL.lpszHostName     = szHostName;       crackedURL.dwHostNameLength = sizeof(szHostName);       crackedURL.lpszUrlPath      = szUrlPath;       crackedURL.dwUrlPathLength  = sizeof(szUrlPath);       InternetCrackUrl(URL_STRING_TEST,(DWORD)strlen(URL_STRING_TEST),0,&crackedURL);       FILE* file = fopen("Onelove.mp3", "wb");       HINTERNET hInt,hConn,hReq;       //啟用HTTP協議       hInt = InternetOpen("Microsoft Internet Explorer", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);       //建立HTTP串連       hConn = InternetConnect(hInt,crackedURL.lpszHostName,crackedURL.nPort,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);       //建立一個URL請求       hReq = HttpOpenRequest(hConn, "GET", crackedURL.lpszUrlPath, NULL, "", NULL, 0, 0);       char buff[64];       DWORD dwContLen = 0;       DWORD  dwLen;       BOOL   bResult = FALSE;       DWORD nBytesGet = 0;       BOOL   bEnd = FALSE;          DWORD dwRetCode = 0;       DWORD dwSizeOfRq = sizeof(DWORD);       dwSizeOfRq = sizeof(buff);                     if (HttpSendRequest(hReq,NULL,0,NULL,0)           && HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwRetCode, &dwSizeOfRq, NULL)           && dwRetCode  400)       {           bResult = TRUE;//true;       }                 //查詢檔案大小       if (HttpQueryInfo(hReq, HTTP_QUERY_CONTENT_LENGTH, &buff, &dwSizeOfRq, NULL))           dwContLen = atol(buff);                  //這裡更改發送的檔案請求          // 方法,請求的路徑,版本       string strHeader;   //         strHeader = "GET ";   //         strHeader+=crackedURL.lpszUrlPath;   //         strHeader+= " HTTP/1.1\r\n";          // 主機   //         strHeader+="Host: ";   //         strHeader+= crackedURL.lpszHostName;   //         strHeader+= IntToString(crackedURL.nPort);   //         strHeader+="\r\n";          // 設定接受資料類型              strHeader += "Accept: */*\r\n";       // 設定 禁止用緩衝和緩衝控制              strHeader += "Pragma: no-cache\r\n";               strHeader += "Cache-Control: no-cache\r\n";       // 設定瀏覽器類型       //     strHeader += "User-Agent:Mozilla/4.04[en](Win95;I;Nav)\r\n";        // 設定串連              strHeader += "Connection:Keep-Alive\r\n";       // 佈建要求檔案的大小              string strRange = "Range: bytes=";              strRange+=IntToString(dwContLen/2);              strRange+="-";              strRange+=IntToString(dwContLen);              strRange+"\r\n";              strHeader+=strRange;          /*       INTERNET_BUFFERS BufferIn;       BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur       BufferIn.Next = NULL;        BufferIn.lpcszHeader = strHeader.c_str(); // 要求標頭       BufferIn.dwHeadersLength = strHeader.length();       BufferIn.dwHeadersTotal = 0;       BufferIn.lpvBuffer = NULL;                       BufferIn.dwBufferLength = 0;       BufferIn.dwBufferTotal = 1024; // This is the only member used other than dwStructSize       BufferIn.dwOffsetLow = 0;       BufferIn.dwOffsetHigh = 0;       */       hReq = HttpOpenRequest(hConn, "GET", crackedURL.lpszUrlPath, NULL, "", NULL, 0, 0);       bool bTrue = HttpAddRequestHeaders(hReq,strHeader.c_str(), -1,HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE  );           if (HttpSendRequest(hReq,NULL,0,NULL,0)           && HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwRetCode, &dwSizeOfRq, NULL)           && dwRetCode  400)       {           bResult = TRUE;//true;       }      //  bool bTrue = HttpSendRequestExA(hReq,&BufferIn,NULL,NULL,0);       while(TRUE)       {           if (bResult)            {               //開始讀取檔案               bResult = InternetReadFile(hReq, szBuffer, sizeof(szBuffer), &dwLen);               if (bResult)               {                   cout<<"reading ... "<<(nBytesGet*100/dwContLen)<<endl;                   nBytesGet += dwLen;                   if (dwLen == 0)                   {                       bEnd = TRUE;                       break;                   }                   fwrite(szBuffer, 1, dwLen, file);               }           }           else //資料接受完畢           {               break;           }          }          fclose(file);      }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.