代码分析:
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define true 1
#define false 0
typedef unsigned int bool;
size_t readData(void *ptr, size_t size, size_t nmemb, void *stream)
{
char buf[10240] = {'\0'};
strncpy(buf, ptr ,10240);
printf("===================================get Data=====================\n");
printf("%s\n",buf);
}
bool postUrl()
{
CURL *curl;
CURLcode res;
char *postString=NULL;
char *img1[12];
char *img2[12];
char *key = "7AVtT3g3TRKnMPXGkNALGA";
char *secret = "3d2252223b274c429d99ac7a5b5b6482";
int typeId = 21;
char *format = "xml";
system("base64 1.jpg > photo3"); //将base64生成的文件信息导到photo3文件中来
int fd = open("./photo3",O_RDWR);//打开photo3文件
int filelen = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET); //计算文件都大小
char *bufpic1 = (char *)malloc(filelen + 2);
memset(bufpic1, 0, filelen+2);
read(fd, bufpic1, filelen);//从文件中读取出来
close(fd);
system("base64 2.jpg > photo4");
fd = open("./photo4",O_RDWR);
filelen = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
char *bufpic2 = (char *)malloc(filelen + 2);
memset(bufpic2, 0, filelen+2);
read(fd, bufpic2, filelen);
close(fd);
int len = strlen(key) + strlen(secret) + strlen(bufpic1) + strlen(bufpic2) + 124;//计算拼接的字符总长度
postString = (char *)malloc(len);
memset(postString , '\0', len);
sprintf(postString,"&img1=%s&img2=%s&key=%s&secret=%s&typeId=%d&format=%s",bufpic1,bufpic2,key,secret,21,format );
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt"); // 指定cookie文件
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postString); //指定post内容
curl_easy_setopt(curl, CURLOPT_URL, "https://netocr.com/api/faceliu.do"); //指定url
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, readData); //将返回http头输出到fp指定的文件
res = curl_easy_perform(curl);
printf("OK: %d\n",res);//将请求的结果打印出来
curl_easy_cleanup(curl);
}
return true;
}
int main(void)
{
// getUrl("/tmp/get.html");
postUrl();
return 0;
}
运行结果: