用socket怎么获得javaWeb返回的json
2个回答
2016-08-05 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
用socket获得javaWeb返回的json的方法:
1、编写客户端解析json的方法client.c代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <json/json.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
/* all previous code until
printf("Size of string- %lu\n", sizeof(json_object_to_json_string(jobj)))*/
char temp_buff[MAX_SIZE];
if (strcpy(temp_buff, json_object_to_json_string(jobj)) == NULL)
{
perror("strcpy");
return EXIT_FAILURE;
}
if (write(fd, temp_buff, strlen(temp_buff)) == -1)
{
perror("write");
return EXIT_FAILURE;
}
printf("Written data\n");
return EXIT_SUCCESS;
}
2、服务端生成json的server.c代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <json/json.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
/* all previous code until
printf("Reading from client\n"); */
ssize_t r;
char buff[MAX_SIZE];
for (;;)
{
r = read(connfd, buff, MAX_SIZE);
if (r == -1)
{
perror("read");
return EXIT_FAILURE;
}
if (r == 0)
break;
printf("READ: %s\n", buff);
}
return EXIT_SUCCESS;
}
其中用json_object_to_json_string把服务端返回的json对象转换成json字符串,传入解析器进行读取。
1、编写客户端解析json的方法client.c代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <json/json.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
/* all previous code until
printf("Size of string- %lu\n", sizeof(json_object_to_json_string(jobj)))*/
char temp_buff[MAX_SIZE];
if (strcpy(temp_buff, json_object_to_json_string(jobj)) == NULL)
{
perror("strcpy");
return EXIT_FAILURE;
}
if (write(fd, temp_buff, strlen(temp_buff)) == -1)
{
perror("write");
return EXIT_FAILURE;
}
printf("Written data\n");
return EXIT_SUCCESS;
}
2、服务端生成json的server.c代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <json/json.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
/* all previous code until
printf("Reading from client\n"); */
ssize_t r;
char buff[MAX_SIZE];
for (;;)
{
r = read(connfd, buff, MAX_SIZE);
if (r == -1)
{
perror("read");
return EXIT_FAILURE;
}
if (r == 0)
break;
printf("READ: %s\n", buff);
}
return EXIT_SUCCESS;
}
其中用json_object_to_json_string把服务端返回的json对象转换成json字符串,传入解析器进行读取。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询