Train_Identify_arm/ai_matrix/myhttp/myhttp.cpp

90 lines
2.1 KiB
C++
Raw Normal View History

2024-06-19 06:35:05 +00:00
#include "myhttp.h"
namespace ai_matrix
{
MyHttp *MyHttp::ins = nullptr;
MyHttp::GarbageCollector MyHttp::gc;
std::mutex MyHttp::mx;
MyHttp *MyHttp::getins()
{
//˫<><CBAB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȷ<EFBFBD><C8B7><EFBFBD>̰߳<DFB3>ȫ
if (ins == nullptr)
{
std::lock_guard<std::mutex> guard(mx); //<2F><>ֹ<EFBFBD><EFBFBD><ECB3A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ܽ<EFBFBD><DCBD><EFBFBD>
if (ins == nullptr)
{
ins = new MyHttp();
}
}
return ins;
}
std::string MyHttp::socketHttp(std::string host, std::string request)
{
int sockfd;
struct sockaddr_in address;
struct hostent *server;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_port = htons(8100);
server = gethostbyname(host.c_str());
memcpy((char *)&address.sin_addr.s_addr, (char*)server->h_addr, server->h_length);
if (-1 == connect(sockfd, (struct sockaddr *)&address, sizeof(address))) {
return "";
}
write(sockfd, request.c_str(), request.size());
char buf[1024 * 1024] = { 0 };
int offset = 0;
int rc;
while (rc = read(sockfd, buf + offset, 1024))
{
offset += rc;
}
close(sockfd);
buf[offset] = 0;
return buf;
}
std::string MyHttp::postData(std::string host, std::string path, std::string post_content)
{
//POST<53><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʽ
std::stringstream stream;
stream << "POST " << path;
stream << " HTTP/1.0\r\n";
stream << "Host: " << host << "\r\n";
stream << "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3\r\n";
stream << "Content-Type:application/x-www-form-urlencoded\r\n";
stream << "Content-Length:" << post_content.length() << "\r\n";
stream << "Connection:close\r\n\r\n";
stream << post_content.c_str();
return socketHttp(host, stream.str());
}
std::string MyHttp::getData(std::string host, std::string path, std::string get_content)
{
//GET<45><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʽ
std::stringstream stream;
stream << "GET " << path << "?" << get_content;
stream << " HTTP/1.0\r\n";
stream << "Host: " << host << "\r\n";
stream << "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3\r\n";
stream << "Connection:close\r\n\r\n";
return socketHttp(host, stream.str());
}
}