现在网络中html保存到文件也可以保存图片

本文介绍了一个使用C++实现的简单网络文件下载程序。该程序通过MFC库中的CInternetSession类来建立HTTP连接,并从指定URL下载文件到本地磁盘。文章详细展示了如何解析URL、发起GET请求、读取响应内容并将其保存到文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有可能你看不懂,那就百度一下

头文件包含#include <afxinet.h>

如果地址是图片那就把文件名该文图片就可以了

int CTools::get_url_file(CString str_url,CString str_file)
{

	USES_CONVERSION;
	CInternetSession session;
	CHttpConnection* pHttpConnection = NULL;
	CHttpFile *pHttpFile = NULL;
	CString strServer, strObject;
	INTERNET_PORT wPort;
	DWORD dwType;

	if (!AfxParseURL(str_url, dwType, strServer, strObject, wPort))
	{
		//WriteLog(L"error.log", L"可能是你的配置文件接口没写,或者是接口格式有问题!");
		return 0;//URL解析错误
	}
	pHttpConnection = session.GetHttpConnection(strServer, wPort);
	pHttpFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
	int result(-3);
	try
	{
		result = pHttpFile->SendRequest();
	}
	catch (CMemoryException* e)
	{
		//WriteLog(L"error.log", L"内存出错!");
	}
	catch (CFileException* e)
	{
		//WriteLog(L"error.log", L"打开文件失败!");
	}
	catch (CException* e)
	{
		//WriteLog(L"error.log", L"请检查服务器接口地址是否可以访问?");
	}

	if (result == -3 || result == 0)
	{
		//WriteLog(L"error.log", strURL + L"HTTP 请求失败");
		return -1;
	}
	DWORD dwRet;
	pHttpFile->QueryInfoStatusCode(dwRet);
	if (dwRet == HTTP_STATUS_OK)
	{
		CFile file;
		file.Open(str_file, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyNone, 0);

		char *pszBuffer = new char[1024];
		UINT nRead = pHttpFile->Read(pszBuffer, 1024);
		//szpHtmlSoure = A2T(pszBuffer);*/


		while (nRead > 0)
		{
			file.Write(pszBuffer, nRead);
			nRead = pHttpFile->Read(pszBuffer, 1024);
		}
		file.Close();
		delete[]pszBuffer;
	}
	else
	{
		CString stemp;
		stemp.Format(L"请求失败:%d 地址:", dwRet);
		//WriteLog(L"error.log", stemp + strURL);
	}
	if (pHttpFile != NULL)
	{
		pHttpFile->Close();
		delete pHttpFile;
		pHttpFile = 0;
	}
	if (pHttpConnection != NULL)
	{
		pHttpConnection->Close();
		delete pHttpConnection;
		pHttpConnection = 0;
	}
	session.Close();
	return dwRet;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值