C++ WinInet API 断点续传

头文件:


#pragma  once 
 
#include  
 
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(); 
 
// ID 号转String 
extern string IdToString( unsigned int nID); 
 
// 提取出文件名字 根据完全路径提取出文件名字 
extern string GetFileName(string strsrc); 
 
// 错误打应 
extern void ErrorExit();

 


cpp文件 :

// #include "stdafx.h"   
   
#include "Utility.h"   
#include    
#include    
    
   
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;   
}   
   
// ID 号转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    
#include    
#include    
#include    
#include    
#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)<


你可能感兴趣的:(C++ WinInet API 断点续传)