ETTimeManage.cpp 2.43 KB
#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");
}