您当前的位置:首页 > 计算机 > 编程开发 > C语言

Libcurl库使用发送单个文件及多个文件demo

时间:01-21来源:作者:点击数:

Libcurl库使用发送单个文件及多个文件demo

demo:

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#include <stdlib.h>

#define PERM 0
char * name = "curl.c";

int main()
{
  CURL *curl;
  CURLcode rcode;
  char *url = "192.168.1.100";
  char *head_t = "66666666";
  char heads[1024];
  struct curl_httppost *formpost=NULL;
  struct curl_httppost *lastptr=NULL;
  struct curl_slist *headers=NULL; /* init to NULL is important */
  sprintf(heads,"head-sky:%s",head_t);

  headers = curl_slist_append(headers, heads);

  rcode = curl_global_init(CURL_GLOBAL_NOTHING);
  if (CURLE_OK != rcode)
    goto err1;

  curl = curl_easy_init();
  if (NULL == curl)
    goto err2;
#if PERM == 1
  /*设置发送单个文件*/
  curl_formadd(&formpost,
    &lastptr,
    CURLFORM_COPYNAME,"sendfile",
    CURLFORM_FILE, name,
    CURLFORM_END);
#else
    /*设置发送多个文件*/
    struct curl_forms array[3];
    array[0].option = CURLFORM_FILE;
    array[0].value = "curl.c";
    array[1].option = CURLFORM_FILE;
    array[1].value = "1.png";
    array[2].option = CURLFORM_END;
        curl_formadd(&formpost,
          &lastptr,
          CURLFORM_COPYNAME, "sendfile",
           CURLFORM_ARRAY, array,
          CURLFORM_END);
#endif

  curl_formadd(&formpost,
    &lastptr,
    CURLFORM_COPYNAME, "filename",
    CURLFORM_COPYCONTENTS, name,
    CURLFORM_END);


  curl_formadd(&formpost,
    &lastptr,
    CURLFORM_COPYNAME, "submit",
    CURLFORM_COPYCONTENTS, "send",
    CURLFORM_END);

  //设置发送http头部
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  //设置url
  curl_easy_setopt(curl, CURLOPT_URL, url);
  //设置http以post方式请求
  curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
  //设置超时时间
  curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);

  //发送数据
  rcode = curl_easy_perform(curl);

  curl_formfree(formpost);
  curl_easy_cleanup(curl);
  curl_slist_free_all(headers);
  curl_global_cleanup();
  return 0;
err2:
    curl_global_cleanup();
err1:
    return;
}

调试时可使用网络调试助手,创建一个tcp server端,使用80端口,接收http请求。

如此在调试助手上即可看到发送的文件及头部。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门