c_cpp Ç发送HTTP
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp Ç发送HTTP相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 14930
#define BACKLOG 10
#define BUFFLEN 2000
#define HEADLEN 512
typedef struct MSG
{
int len;
char * buf;
}MSG,pMSG;
using namespace std;
char * MakeHttpPost(char *host, char *szData)
{
if(NULL == szData)
{
szData = "";
}
int iDataLen = strlen(szData);
int iPostLen = iDataLen + HEADLEN;
char *szPost = NULL;
szPost = (char* )malloc(sizeof(char) * iPostLen);
if(NULL == szPost)
{
printf("Function %s Malloc error!\n", __FUNCTION__);
return NULL;
}
memset(szPost, 0, sizeof(char) * iPostLen);
snprintf(szPost, iPostLen, "POST /WatchData/ HTTP/1.1\nHost: %s\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:58.0) Gecko/20100101 Firefox/58.0\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nAccept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\nContent-Type: application/x-www-form-urlencoded\nContent-Length: %d\nCookie:\nDNT: 1\nConnection: Keep-Alive\nUpgrade-Insecure-Requests: 1\n\n%s\r\n\r\n",host, iDataLen, szData);
return szPost;
}
int clientLinkTCP(int *sockfd, const char *IPaddr, int port, struct sockaddr_in *servaddr)
{
if ((*sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("socket");
return -1;
}
bzero(servaddr, sizeof(*servaddr));
(*servaddr).sin_family = AF_INET;
(*servaddr).sin_port = htons(port);
inet_aton(IPaddr, &(*servaddr).sin_addr);
if(connect(*sockfd, (struct sockaddr *) servaddr, sizeof(struct sockaddr_in)) == -1)
{
perror("connect");
return -2;
}
return 0;
}
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in servaddr;
clientLinkTCP(&sockfd,"192.168.1.204",8000,&servaddr);
for(int i = 0; i < 5; i++)
{
char host[128] = "192.168.1.204:8000";
clientLinkTCP(&sockfd,"192.168.1.204",8000,&servaddr);
MSG msg;
memset(&msg, 0, sizeof(msg));
char temp[128] = {0};
sprintf(temp,"id=username_%d",i);
char *head = NULL;
head = MakeHttpPost(host,temp);
msg.len = strlen(head);
printf("head:%s\n",head);
msg.buf = head;
int iSendLen = 0;
while(iSendLen < msg.len){
iSendLen += send(sockfd, msg.buf+iSendLen, msg.len, 0);//发送字符串
}
free(head);
int iRecvLen = 0;
// sleep(1);
}
close(sockfd);
return 0;
}
以上是关于c_cpp Ç发送HTTP的主要内容,如果未能解决你的问题,请参考以下文章