ETTimeManage.cpp
2.43 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "stdafx.h"
#include "etradeclient/utility/ETTimeManage.h"
//#include "etradeclient/utility/logon_mgr.h"
#include "etradeclient/utility/win_http.h"
#include "etradeclient/utility/logging.h"
#include "etradeclient/utility/url_config.h"
#include "etradeclient/utility/application_config.h"
#include "etradeclient/utility/string_converter.h"
//#include "etradeclient/utility/session.h"
#include <boost/property_tree/ptree.hpp>
#include "etradeclient/boost_patch/property_tree/json_parser.hpp" // WARNIING! Make sure to include our patched version.
#include <sstream>
#include "etradeclient/browser/session.h"
CETTimeManage::CETTimeManage()
{
}
CETTimeManage::~CETTimeManage()
{
}
CString CETTimeManage::GetServerTime()
{
CString sLog;
LOG_TRACE(_T("开始获取服务器时间!"));
try
{
const uint32_t kHTTPOK = 200;
WinHttp win_http;
auto& url_cfg = URLConfig::Instance();
win_http.ConnectHost(url_cfg.Host(), url_cfg.Port(), url_cfg.IsHttps());
auto& request = win_http.OpenRequest(WinHttp::Method::GET, url_cfg.ServerTimePath());
if (url_cfg.IsHttps())
{
auto& app_cfg = ApplicationConfig::Instance();
request.SetClientCertificate(app_cfg.ClientCertStore(), app_cfg.ClientCertSubject());
}
request.SetCookies(Session::Instance().Cookies());
request.Send();
uint32_t status_code = request.GetResponseStatus();
if (kHTTPOK != status_code)
{
std::string err_msg = "网络请求错误! 错误码: " + std::to_string(status_code);
LOG_ERROR(str_2_wstr(err_msg.c_str()));
}
std::string response_body = request.ReadResponseBody();
if (response_body.empty())
{
LOG_ERROR(L"获取服务器响应数据失败,请确保网络连接正常!");
}
m_cTime = GetResponseData(response_body); // If log in failed.
}
catch (std::exception& ex)
{
LOG_ERROR(gbk_2_wstr(ex.what()));
m_cTime = CTime::GetCurrentTime();
}
return m_cTime.Format("%H:%M:%S");
}
CTime CETTimeManage::GetResponseData(std::string sResponse)
{
CTime cServerTime;
namespace PT = boost::property_tree;
try
{
PT::ptree pServerTimeTree;
std::stringstream ssTime;
ssTime << sResponse;
PT::read_json(ssTime, pServerTimeTree);
cServerTime = CTime(pServerTimeTree.get<__time64_t>("message"));
}
catch (...)
{
LOG_ERROR(L"解析服务器返回返回服务器时间时出错!请确认返回数据不为空,返回的数据格式为正确的Json格式!");
return false;
}
return cServerTime;
}
CString CETTimeManage::UpdateTime()
{
m_cTime = m_cTime + CTimeSpan(1);
return m_cTime.Format("%H:%M:%S");
}