libcurl和json的初次使用
apache安装
sudo apt-get install apache2
静态网页位置:/var/www/html
apache可执行程序CGI存放位置:/usr/lib/cgi-bin/
cgi模块支持启用
cd /etc/apache2/mods-enable
sudo ln -s ../mods-available/cgid.conf
sudo ln -s ../mods-available/cgid.load
sudo ln -s ../mods-available/cgi.load
sudo /etc/init.d/apache2 restart
libcurl库的安装
sudo apt-get install curl
安装curl命令,该命令将curl安装/usr/bin
sudo apt-get install libcurl4-openssl-dev
来安装libcurl,libcurl的安装路径
头文件:/usr/include/curl
库目录:/usr/lib
json
用git克隆获取源代码
命令:git clone https://github.com/json-c/json-c.git
示例代码
代码说明:(理解为客户端,必须放在/usr/lib/cgi-bin/ 目录下编译)
1.将用户名和密码打包成JSON格式
2.用libcurl以post的方式将数据提交给服务器,并访问a.out (CGI程序),此程序验证用户名和密码是否正确。
编译:gcc *.c cJSON.c -lcurl -lm (cJSON.c,cJSON.h库拷贝到当前目录)
#include <stdlib.h>
#include <curl/curl.h>
#include "cJSON.h"
int main()
{
cJSON* root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "username", "aa");
cJSON_AddStringToObject(root, "password", "bb");
char* buf = cJSON_Print(root);
CURL* curl = curl_easy_init();
// {username:"aa", password:"bb"}
// 默认是GET方式,如果想改成POST方式
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf); // username=aa&password=bb
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/cgi-bin/a.out");
// POST方式
curl_easy_perform(curl);
cJSON_Delete(root);
free(buf);
}
代码说明:
1.此为上述代码的a.out(CGI程序),将发送过来的JSON打包格式buf读取出来
2.buf读取出来后,再通过JSON解包,就可以获取用户名和密码进行验证。
编译:gcc *.c cJSON.c -lm (cJSON.c,cJSON.h库拷贝到当前目录)
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
extern char** environ;
int main()
{
// 规定
printf("content-type: text/html\n\n");
int content_len = atoi( getenv("CONTENT_LENGTH") );
char* buf = malloc(content_len + 1);
buf[content_len] = 0;
// 读的是客户端发送过来的POST数据
fread(buf, content_len, 1, stdin);
cJSON* root = cJSON_Parse(buf);
cJSON* user = cJSON_GetObjectItem(root, "username");
cJSON* pass = cJSON_GetObjectItem(root, "password");
if(strcmp(user->valuestring, "aa") == 0
&& strcmp(pass->valuestring, "bb") == 0)
{
printf("login ok\n");
}
else
{
printf("login error\n");
}
}