【转】c++ http下载文件

复制代码
#include 
#include 
#define RECVPACK_SIZE 2048
bool DownloadSaveFiles(char* url,char *strSaveFile) {//下载文件并保存为新文件名
    bool ret=false;
    CInternetSession Sess("lpload");
    Sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT     , 2000); //2秒的连接超时
    Sess.SetOption(INTERNET_OPTION_SEND_TIMEOUT        , 2000); //2秒的发送超时
    Sess.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT     , 2000); //2秒的接收超时
    Sess.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT   , 2000); //2秒的发送超时
    Sess.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 2000); //2秒的接收超时
    DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_RELOAD ;

    CHttpFile* cFile   = NULL;
    char      *pBuf    = NULL;
    int        nBufLen = 0   ;
    do {
        try{
            cFile = (CHttpFile*)Sess.OpenURL(url,1,dwFlag);
            DWORD dwStatusCode;
            cFile->QueryInfoStatusCode(dwStatusCode);
            if (dwStatusCode == HTTP_STATUS_OK) {
                //查询文件长度
                DWORD nLen=0;
                cFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, nLen);
                //CString strFilename = GetFileName(url,TRUE);
                nBufLen=nLen;
                if (nLen <= 0) break;//

                //分配接收数据缓存
                pBuf = (char*)malloc(nLen+8);
                ZeroMemory(pBuf,nLen+8);

                char *p=pBuf;
                while (nLen>0) {
                    //每次下载8K
                    int n = cFile->Read(p,(nLenClose();
        Sess.Close();
        delete cFile;
    }
    return ret;
}
int main() {
    DownloadSaveFiles("http://www.nirsoft.net/utils/nircmd.zip","d:\\cppdld_nircmd.zip");
    return 0;
}
复制代码

http://bbs.csdn.net/topics/390052882

转载于:https://www.cnblogs.com/tiandsp/p/7440837.html

你可能感兴趣的:(【转】c++ http下载文件)