-
Notifications
You must be signed in to change notification settings - Fork 1
/
winhttp-download.h
67 lines (56 loc) · 1.53 KB
/
winhttp-download.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
** ͬ²½GET·½Ê½ÏÂÔØ
** winhttp
** author
*/
#ifndef ULT_WINHTTPDOWNLOAD_H_
#define ULT_WINHTTPDOWNLOAD_H_
#include "./winhttp-request.h"
#include "./file-io.h"
#include "./file-dir.h"
#include <string>
namespace ult {
namespace detail {
struct HttpDownloadString {
HRESULT operator()(const std::wstring& url, std::string* s) {
WinHttpRequest req;
RETURN_IF_FAILED(req.Request(url));
LPVOID buffer;
DWORD readed;
while (SUCCEEDED(req.ReadData(&buffer, &readed)) && readed != 0) {
s->append((char*)buffer, readed);
}
return S_OK;
}
};
struct HttpDownloadFile {
HRESULT operator()(const std::wstring& url, const std::wstring& file) {
WinHttpRequest req;
RETURN_IF_FAILED(req.Request(url));
LPVOID buffer;
DWORD readed;
std::wstring file_folder(ult::GetUpperDirectory(file));
if (!ult::CreateDirectories(file_folder)) {
return HRESULT_FROM_WIN32(::GetLastError());
}
ult::File down_file;
if (!down_file.Create(file, true)) {
return HRESULT_FROM_WIN32(::GetLastError());
}
DWORD written;
while (SUCCEEDED(req.ReadData(&buffer, &readed)) && readed != 0) {
down_file.Write(buffer, readed, &written);
}
return S_OK;
}
};
} //namespace detail
inline HRESULT HttpDownloadString(const std::wstring& url, std::string* s) {
return detail::HttpDownloadString()(url, s);
}
inline HRESULT HttpDownloadFile(const std::wstring& url, const std::wstring& file) {
return detail::HttpDownloadFile()(url, file);
}
} //namespace ult
#endif