C/C++实现http下载文件

一、使用MFC winhttp下载

#include <afx.h>
#include <afxinet.h>
#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,(nLen<RECVPACK_SIZE)?nLen:RECVPACK_SIZE);
                    //接收完成退出循环
                    if (n <= 0) break;//
                    //接收缓存后移
                    p+= n ;
                    //剩余长度递减
                    nLen -= n ;
                }
 
                //如果未接收完中断退出
                if (nLen != 0) break;
 
                //接收成功保存到文件
 
                CFile file(strSaveFile, CFile::modeCreate | CFile::modeWrite);
                file.Write(pBuf,nBufLen);
                file.Close();
                ret = true;
            }
        } catch(...) {
            break;//
        }
    } while(0);
 
    //释放缓存
    if (pBuf) {
        free(pBuf);
        pBuf=NULL;
        nBufLen = 0 ;
    }
 
    //关闭下载连接
    if (cFile) {
        cFile->Close();
        Sess.Close();
        delete cFile;
    }
    return ret;
}
int main() {
    DownloadSaveFiles("http://www.nirsoft.net/utils/nircmd.zip","d:\\cppdld_nircmd.zip");
    return 0;
}

二、使用WinInet API

void download(const char *Url, const char *filename)
{
	byte Temp[1024];
	ULONG Number = 1;
 
	FILE *stream;
	HINTERNET hSession = InternetOpen("RookIE/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession != NULL)
	{
		HINTERNET handle2 = InternetOpenUrl(hSession, Url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);
		if (handle2 != NULL)
		{
 
 
			if ((stream = fopen(filename, "wb")) != NULL)
			{
				while (Number > 0)
				{
					InternetReadFile(handle2, Temp, MAXBLOCKSIZE - 1, &Number);
 
					fwrite(Temp, sizeof(char), Number, stream);
				}
				fclose(stream);
			}
 
			InternetCloseHandle(handle2);
			handle2 = NULL;
		}
		InternetCloseHandle(hSession);
		hSession = NULL;
	}
}

三、使用Windows提供的urlmon

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <windows.h>
#include <urlmon.h>

#pragma comment(lib, "urlmon.lib")

using namespace std;

BOOL FileExistsStatus(const CHAR* path)
{
	DWORD dwAttribute = GetFileAttributes(path);
	if (dwAttribute == 0XFFFFFFFF) return false; //0XFFFFFFFF表示文件不存在
	else return true;
}

BOOL DownloadFiles(const CHAR* url, const CHAR* downloadPath)
{
	if (URLDownloadToFile(NULL, url, downloadPath, 0, 0) == S_OK && FileExistsStatus(downloadPath)) return true;
	else return false;
}

int main(int argc, char* argv[])
{
	if (DownloadFiles(argv[1], argv[2])) printf("OK!\n");
	else printf("Error!\n");
	return 0;
}

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值