色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

c json post請求

C語言中,我們經(jīng)常需要用到j(luò)son數(shù)據(jù)格式。而在進(jìn)行post請求的時候,也需要將數(shù)據(jù)轉(zhuǎn)化為json格式進(jìn)行傳輸。本文將介紹使用C語言進(jìn)行json post請求的方法。

#include#include#include#include#include#include#include#include#include#define JSON_DATA "{\"name\":\"example\",\"age\":20}"
int main(int argc, char *argv[]) {
struct sockaddr_in addr;
int sock_fd, ret;
char buf[1024];
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd< 0) {
perror("socket error");
return -1;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(sock_fd, (struct sockaddr*)&addr, sizeof(addr));
if (ret< 0) {
perror("connect error");
return -1;
}
char *http_post = "POST /api HTTP/1.1\r\n"
"Host: localhost\r\n"
"Content-Type: application/json; charset=utf-8\r\n"
"Content-Length: 26\r\n"
"\r\n"
JSON_DATA;
ret = send(sock_fd, http_post, strlen(http_post), 0);
if (ret< 0) {
perror("send error");
return -1;
}
int total_len = 0;
while (1) {
ret = recv(sock_fd, buf + total_len, sizeof(buf) - total_len, 0);
if (ret< 0) {
perror("recv error");
return -1;
}
total_len += ret;
if (ret == 0 || strstr(buf, "\r\n\r\n") != NULL) {
break;
}
}
printf("received: %s\n", buf);
close(sock_fd);
return 0;
}

在這個示例中,我們使用了一個簡單的json字符串,內(nèi)容為{"name":"example","age":20}。在進(jìn)行post請求時,需要設(shè)置Content-Type為application/json,并將json字符串作為請求body發(fā)送出去。在接收http響應(yīng)時,我們使用了recv函數(shù),將響應(yīng)數(shù)據(jù)接受到buf中,直到接受完整個響應(yīng)。