废话不多说,直接上代码
//#include <stdlib.h> #include "winsock2.h" #include <string> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define IPSTR "127.0.0.1" //服务器IP地址; #define PORT 8080 //服务器端口; #define BUFSIZE 1024 class httpClient { std::string host; std::string path; std::string post_content; public: std::string httpSend(std::string httpHeader); std::string httpGet(std::string host, std::string path); std::string httpPost(std::string host, std::string path,std::string post_content); }; std::string httpClient::httpSend(std::string httpHeader) { //POST请求方式 std::string ret = ""; // 返回Http Response // 开始进行socket初始化 WSADATA wData; ::WSAStartup(MAKEWORD(2, 2), &wData); SOCKET clientSocket = socket(AF_INET, 1, 0); struct sockaddr_in ServerAddr = {0}; ServerAddr.sin_addr.s_addr = inet_addr(IPSTR); ServerAddr.sin_port = htons(PORT); ServerAddr.sin_family = AF_INET; int errNo = connect(clientSocket, (sockaddr*)&ServerAddr, sizeof(ServerAddr)); if(errNo == 0) { errNo = send(clientSocket, httpHeader.c_str(), httpHeader.length(), 0);//发送头文件 if(errNo > 0) { std::cout << "发送成功" << std::endl; } else { std::cout << "errNo:" << errNo << std::endl; return ret; } // 接收 char bufRecv[3069] = {0}; errNo = recv(clientSocket, bufRecv, 3069, 0); if(errNo > 0) { ret = bufRecv;// 如果接收成功,则返回接收的数据内容 char *p; char *delims= {"\n"} ; p=strtok(bufRecv,"\n"); int i = 0; while(p!=NULL) { if(i == 13){ // printf("word: %s\n",p); //对获取的数据进行分割,获取每一行的数据 ret = p; } i++; p=strtok(NULL,delims); } return ret; } else { std::cout << "errNo:" << errNo << std::endl; return ret; } } else { errNo = WSAGetLastError(); std::cout << "errNo:" << errNo << std::endl; } // socket环境清理 ::WSACleanup(); } /** Get 请求 */ std::string httpClient::httpGet(std::string host, std::string path) { std::string httpHeader; httpHeader= "GET "+path+" HTTP/1.1\r\n" "Host: "+host+"\r\n" "User-Agent: IE or Chrome\r\n" "Accept-Type: */*\r\n" "Connection: Close\r\n\r\n"; return httpSend(httpHeader); } /** Post 请求 */ std::string httpClient::httpPost(std::string host, std::string path,std::string post_content) { std::string httpHeader; char lenChar[16]; //这个长度根据需要吧 sprintf(lenChar, "%d", post_content.length()); std::string len(lenChar); httpHeader= "POST "+path+" HTTP/1.1\r\n" "Host: "+host+"\n" "Connection: Close\r\n" "Content-Type: application/json\n" "Content-Length: "+ len +"\n\n" +post_content; return httpSend(httpHeader); } int main() { httpClient *http = new httpClient(); // ***********************GET***************************** std::cout<<"Get:"<< http->httpGet("127.0.0.1:8080", "/admin") <<std::endl; // ***********************POST***************************** std::string message= "{\"Type\":1, " " \"Dev\":1,\"Ch\":1, " " \"Data\":{ " " \"AlarmCh\":1,\"AlarmOutCount\":1,\"AlarmType\":1 " "}}"; std::cout<<"POST:"<< http->httpPost("127.0.0.1:8080", "/withBody1",message)<<std::endl; }
C语言版本:
https://blog.csdn.net/weixin_45721882/article/details/120932661