libcurl http post文件同时接收服务器响应文件
下载libcurl和zlib源文件,及hfs
- libcurl和zlib建议去官方网站或者GitHub下载;
- hfs是测试用的服务器,随便搜一下就找到了;
编译库文件
本人的测试系统选择的centos,默认使用的是系统自带的gcc,下面编译简单配置:
- .libcurl配置:
./configure --prefix=$(pwd)/install
make;make install; - zlib配置:
./configure --prefix=$(pwd)/install
make;make install
将用到的库文件和头文件拷贝出来,放在要测试的工程里面。
测试代码
测试程序是参考网上各位大神的博客综合起来的,感谢各位大神。测试代码如下:
#include <stdio.h>
#include <string.h>
#include "./curl/curl.h"
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
int main(int argc, char *argv[])
{
CURL *curl;
CURLcode res;
struct curl_httppost *formpost=NULL;
struct curl_httppost *lastptr=NULL;
struct curl_slist *headerlist=NULL;
static const char buf[] = "Expect:";
curl_global_init(CURL_GLOBAL_ALL);
/* Fill in the file upload field */
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "sendfile",
CURLFORM_FILE, "post.tar",
CURLFORM_END);
/* Fill in the submit field too, even if this is rarely needed */
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "submit",
CURLFORM_COPYCONTENTS, "send",
CURLFORM_END);
curl = curl_easy_init();
/* initalize custom header list (stating that Expect: 100-continue is not
wanted */
headerlist = curl_slist_append(headerlist, buf);
if(curl) {
/* what URL that receives this POST */
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.8.2:8000/");
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
FILE *pagefile;
//写入到文件
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
pagefile = fopen("respone.tar", "wb");
if (pagefile)
{
curl_easy_setopt(curl, CURLOPT_WRITEDATA, pagefile);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
}
fclose(pagefile);
printf("************************************\n");
}else{
printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
}
#if 0
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
#endif
/* always cleanup */
curl_easy_cleanup(curl);
/* then cleanup the formpost chain */
curl_formfree(formpost);
/* free slist */
curl_slist_free_all (headerlist);
}
return 0;
}
编译生成测试程序
- gcc http_post.c -o post_response -L. -lcurl -lpthread -lz
- 运行./post_response
- 运行之前需要将hfs打开并设置好,就可以看到上传的文件,hfs设置参考链接: https://blog.csdn.net/nicholas_duan/article/details/103126952.
- 使用hfs测试中,response的文件时一个html文件,我的测试中,使用的是专门写的一个工具,具体根据需要自己来找到适合自己的服务器;
结语
这个测试只是用于本人的学习记录,可能有不少错误,如您发现,请私信或留言,帮助我改进,共同进步。