Last active
March 3, 2022 22:25
-
-
Save stephanelpaul/a81ba1e293ef386cc864ece173c04926 to your computer and use it in GitHub Desktop.
c++ socket http json post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <arpa/inet.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <sys/wait.h> | |
#include <errno.h> | |
#include <netinet/in.h> | |
#include <stdio.h> | |
#include <netdb.h> | |
#include <unistd.h> | |
#define SA struct sockaddr | |
#define MAX_LINE 4096 | |
#define MAX_SUB 1024 | |
#define JSON_TEMPLATE "{\"key1":\"%s\"}" | |
extern int h_errno; | |
ssize_t process_http(int socketfd, char *host, char *page, char *poststr) { | |
char sendline[MAX_LINE + 1], recvline[MAX_LINE +1]; | |
ssize_t n; | |
snprintf(sendline, MAX_SUB, | |
"POST %s HTTP/1.0\r\n" | |
"Host: %s\r\n" | |
"Content-type: application/json\r\n" | |
"Content-length: %d\r\n\r\n" | |
"%s", page, host, (int)strlen(poststr), poststr); | |
write(socketfd, sendline, strlen(sendline)); | |
while((n = read(socketfd, recvline, MAX_LINE))> 0) { | |
recvline[n] = '\0'; | |
printf("%s", recvline); | |
} | |
return n; | |
} | |
int main() { | |
if ((hptr = gethostbyname(SERVER_BASE_URL)) == NULL) { | |
fprintf(stderr, " gethostbyname error for host: %s: %s", SERVER_BASE_URL, hstrerror(h_errno)); | |
} | |
char str[50]; | |
if (hptr->h_addrtype == AF_INET && (pptr = hptr->h_addr_list) != NULL) { | |
printf("address: %s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str))); | |
} else { | |
fprintf(stderr, "Error call inet_stop\n"); | |
} | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
bzero(&serveraddr, sizeof(serveraddr)); | |
serveraddr.sin_family = AF_INET; | |
serveraddr.sin_port = htons(80); | |
inet_pton(AF_INET, str, &serveraddr.sin_addr); | |
connect(sockfd, (SA *) &serveraddr, sizeof(serveraddr)); | |
char *postContents = new char[128]; | |
sprintf(postContents, | |
JSON_TEMPLATE, | |
"val1") | |
process_http(postContents); | |
delete []postContents; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment