You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.0 KiB
C++
96 lines
2.0 KiB
C++
#include "HttpClient.h"
|
|
#define CLIENT_FILE_DIR "/ClientFiles";
|
|
#define CMD_GetFileList "GetFileList"
|
|
|
|
static string GetExeDir()
|
|
{
|
|
char buff[_MAX_PATH];
|
|
_getcwd(buff, _MAX_PATH);
|
|
string currPath(buff);
|
|
return string(buff);
|
|
}
|
|
|
|
CHttpClient::CHttpClient(string IP, int Port)
|
|
{
|
|
m_HostIP = IP;
|
|
m_HostPort = Port;
|
|
}
|
|
|
|
CHttpClient::~CHttpClient()
|
|
{
|
|
}
|
|
|
|
|
|
bool CHttpClient::DownloadFile(const string& file_name)
|
|
{
|
|
httplib::Client cli(m_HostIP, m_HostPort);
|
|
auto res = cli.Get(("/download/" + file_name).c_str());
|
|
if (res && res->status == 200)
|
|
{
|
|
string save_path = GetExeDir() + CLIENT_FILE_DIR;
|
|
save_path += "/";
|
|
save_path += file_name;
|
|
// ´ò¿ªÎļþ½øÐÐдÈë
|
|
ofstream file(save_path, ios::binary);
|
|
if (!file)
|
|
{
|
|
cerr << "Failed to save file: " << save_path << endl;
|
|
return false;
|
|
}
|
|
file.write(res->body.c_str(), res->body.size());
|
|
file.close();
|
|
cout << "File downloaded and saved at: " << save_path << endl;
|
|
return true;
|
|
}
|
|
else
|
|
{
|
|
cerr << "Failed to download file. Status code: "
|
|
<< (res ? to_string(res->status) : "No response") << endl;
|
|
return false;
|
|
}
|
|
}
|
|
|
|
bool CHttpClient::SendCmd(const string cmd, string & sRespon)
|
|
{
|
|
httplib::Client cli(m_HostIP,m_HostPort);
|
|
auto res = cli.Get(("/command/" + cmd).c_str());
|
|
|
|
if (res && res->status == 200)
|
|
{
|
|
sRespon = res->body;
|
|
cout << "Command Respon:" << sRespon << endl;
|
|
return true;
|
|
}
|
|
else
|
|
{
|
|
sRespon.clear();
|
|
string sErr = "SendCmd Failed. Status code: ";
|
|
sErr += res ? to_string(res->status) : "No response";
|
|
cerr << sErr << endl;
|
|
return false;
|
|
}
|
|
|
|
}
|
|
|
|
bool CHttpClient::DownloadAllFile()
|
|
{
|
|
string sRespon;
|
|
if (!SendCmd(CMD_GetFileList, sRespon))
|
|
return false;
|
|
|
|
CString FullStr = sRespon.data();
|
|
CString strNameValue; // an individual name, value pair
|
|
|
|
int i = 0; // substring index to extract
|
|
while (AfxExtractSubString(strNameValue, FullStr, i,','))
|
|
{
|
|
if (!strNameValue.IsEmpty())
|
|
{
|
|
DownloadFile(strNameValue.GetBuffer());
|
|
strNameValue.ReleaseBuffer();
|
|
}
|
|
i++;
|
|
}
|
|
return true;
|
|
}
|