zoukankan      html  css  js  c++  java
  • 使用libcurl POST数据和上传文件

    为了具有通用性,将文件的内容读到了fc变量中,fclen是fc的长度。fc也可以是任何其它内容。curl 是 libcurl句柄。演示省略了很多显而易见的步骤。

    1. 普通的post请求,这里用curl_easy_escape对fc做了编码
    std::string data("req=plain");
    data.append("&file=");
    char *efc = curl_easy_escape(curl, fc, fclen);
    data.append(efc)
    curl_free(encoded);

    curl_easy_setopt(curl, CURLOPT_URL, PURGE_URL);
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.size());

    2. multipart/formdata请求
    struct curl_httppost *formpost = 0;
    struct curl_httppost *lastptr  = 0;
    curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "reqformat", CURLFORM_PTRCONTENTS, "plain", CURLFORM_END);
    curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "file", CURLFORM_PTRCONTENTS, fc, CURLFORM_CONTENTSLENGTH, fclen, CURLFORM_END);

    curl_easy_setopt(curl, CURLOPT_URL, URL);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
    curl_easy_perform(curl);
    curl_formfree(formpost);

    3. multipart/formdata请求,不把文件读入fc,其它步骤相同
    curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "file", CURLFORM_FILE, "/path/filename", CURLFORM_END);

    4. 通过put上传文件
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt(curl, CURLOPT_PUT, 1L);
    curl_easy_setopt(curl, CURLOPT_READDATA, fp);   // FILE *fp = fopen("/path/filename");
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, fsize);  // fsize = sizeof /path/filename

    5. 发送自己的Header
    struct curl_slist *slist = 0;
    slist = curl_slist_append(slist, "Blog-X-User: username");
    slist = curl_slist_append(slist, "Blog-X-Signature: signature");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
    curl_slist_free_all(slist);
  • 相关阅读:
    线段树专辑—— pku 1436 Horizontally Visible Segments
    线段树专辑——pku 3667 Hotel
    线段树专辑——hdu 1540 Tunnel Warfare
    线段树专辑—— hdu 1828 Picture
    线段树专辑—— hdu 1542 Atlantis
    线段树专辑 —— pku 2482 Stars in Your Window
    线段树专辑 —— pku 3225 Help with Intervals
    线段树专辑—— hdu 1255 覆盖的面积
    线段树专辑—— hdu 3016 Man Down
    Ajax跨域访问
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9410119.html
Copyright © 2011-2022 走看看