我是c++新手,试着写一个更新函数。
使用URLDownloadToFile下载没有问题,但如果我将URL更改为无效URL,它仍然返回S_OK ...我如何检查下载是否成功?
#include <WinInet.h>
#include <iomanip>
int download_file (const TCHAR urldownload[],const TCHAR target[] )
{
DownloadProgress progress;
IBindStatusCallback* callback = (IBindStatusCallback*)&progress;
SCP(40, NULL); cout << target;
HRESULT status = URLDownloadToFile(NULL, urldownload, target, 0, static_cast<IBindStatusCallback*>(&progress));
Sleep(200);
DeleteUrlCacheEntry(urldownload);
wcout << status;
if (status == S_OK) cout << "yes";
else(cout << "Download failed");
Sleep(10000); return 1;
}
class DownloadProgress : public IBindStatusCallback {
public:
HRESULT __stdcall QueryInterface(const IID &, void **) {
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef(void) {
return 1;
}
ULONG STDMETHODCALLTYPE Release(void) {
return 1;
}
HRESULT STDMETHODCALLTYPE OnStartBinding(DWORD dwReserved, IBinding *pib) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetPriority(LONG *pnPriority) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnLowResource(DWORD reserved) {
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE OnStopBinding(HRESULT hresult, LPCWSTR szError) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetBindInfo(DWORD *grfBINDF, BINDINFO *pbindinfo) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC *pformatetc, STGMEDIUM *pstgmed) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(REFIID riid, IUnknown *punk) {
return E_NOTIMPL;
}
virtual HRESULT __stdcall OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText)
{
//wcout << ulProgress << L" of " << ulProgressMax << endl; Sleep(200);
if (ulProgress != 0 && ulProgressMax != 0)
{
double output = (double(ulProgress) / ulProgressMax)*100;
cout << "\r" << "Downloading: " << fixed << setprecision(2) << output << " % " ; Sleep(20);
}
return S_OK;
}
};
2条答案
按热度按时间gopyfrb31#
MSDN article has the answer为您提供:
URLDownloadToFile
在文件创建失败、下载取消的情况下,也会返回S_OK
。如果szFileName参数中包含文件路径,则在调用URLDownloadToFile
之前,请确保目标目录存在。为了更好地控制下载和下载进度,建议使用IBindStatusCallback
接口。你需要提供一个状态回调来接收异步操作的状态。你的代码片段已经有了基础。
OnProgress
和OnStopBinding
应该会得到下载失败的结果。6l7fqoea2#
include“wininet. h”
String s(String s);HRESULT response = URLDownloadToFile(NULL,(LPCSTR)url,(LPCSTR)default_path,0,NULL);
我希望它有用