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

c 接收post json格式數據格式

李中冰2年前8瀏覽0評論

C語言中,接收Post請求的JSON數據格式需按照以下格式處理:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
int main()
{
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *response = "Hello from server";
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
perror("accept");
exit(EXIT_FAILURE);
}
read(new_socket, buffer, 1024);
printf("%s\n", buffer);
return 0;
}

Post請求中的數據可以通過上述方法獲取。其中,定義request的數據類型為以下格式:

typedef struct Request {
char *body;
	} Request;

然后,解析JSON格式的數據:

char *response_json;
json_object *request_json;
struct Request *request = malloc(sizeof(struct Request));
request->body = buffer;
request_json = json_tokener_parse(request->body);
response_json = get_response(request_json);
send(new_socket, response_json, strlen(response_json), 0);

在獲取的request中,body即為Post請求中的JSON格式數據。通過json_tokener_parse()方法解析body即可得到request_json,后面我們可以通過get_response()方法獲得response的JSON格式數據,發送給客戶端即可。