Cplusplusplusplus互联网学习资源

使用libcurl提交表单信息

2018-10-17  本文已影响1人  云谁之殇

1、登录禅道

测试地址:http://182.151.214.29:7600/zentao

  CURL* easy_handle;
    CURLcode res;
    FILE* fptr;
    curl_slist* http_header = nullptr;

    if ((fptr = fopen(FILENAME, "w+")) == NULL) {
        fprintf(stderr, "fopen file error: %s\n", FILENAME);
        return -1;
    }
    CURLcode code;
    code = curl_global_init(CURL_GLOBAL_ALL);

    if (CURLE_OK != code)
    {
        std::cerr << "init libcurl failed." << std::endl;
        return -1;
    }
    
    std::string strPostFields = "account=username&password=thisispasswordxxxxx&referer=http%3A%2F%2F192.168.2.7%3A7600%2Fzentao%2Fmy%2F";

    easy_handle = curl_easy_init();
    curl_easy_setopt(easy_handle, CURLOPT_URL, "http://182.151.214.29:7600/zentao");
    curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDS, strPostFields.c_str());
    curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, func);   //回调函数,用于保存接收到的数据
    curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, fptr);
    curl_easy_setopt(easy_handle, CURLOPT_POST, 1);
    curl_easy_setopt(easy_handle, CURLOPT_VERBOSE, 1);  
    curl_easy_setopt(easy_handle, CURLOPT_HEADER, 1); 
    res = curl_easy_perform(easy_handle);
    
    curl_easy_cleanup(easy_handle);
    fclose(fptr);
    curl_global_cleanup();
    return res==CURLE_OK;

2、上传图片测试

测试地址:http://thyrsi.com/upload.php

请求头 提交的数据 返回的数据
    CURL* easy_handle;
    CURLcode res;
    FILE* fptr;
    curl_slist* http_headers = nullptr;

    if ((fptr = fopen(FILENAME, "w+")) == NULL) {
        fprintf(stderr, "fopen file error: %s\n", FILENAME);
        return -1;
    }
    CURLcode code;
    code = curl_global_init(CURL_GLOBAL_ALL);

    if (CURLE_OK != code)
    {
        std::cerr << "init libcurl failed." << std::endl;
        return -1;
    }

    curl_httppost *formpost = NULL;
    curl_httppost *lastptr = NULL;

    curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "MAX_FILE_SIZE", CURLFORM_COPYCONTENTS, "200000000", CURLFORM_END);
    curl_formadd(&formpost, &lastptr, 
        CURLFORM_COPYNAME, "uploadimg", 
        CURLFORM_FILE, "C:\\Users\\36240\\Desktop\\timg.jpg",
        CURLFORM_CONTENTTYPE,"image/jpeg", 
        CURLFORM_END);

    easy_handle = curl_easy_init();
    curl_easy_setopt(easy_handle, CURLOPT_URL, "http://thyrsi.com/upload.php");
    curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, write_data);   //回调函数,用于保存接收到的数据
    curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, fptr);
    curl_easy_setopt(easy_handle, CURLOPT_POST, 1);
    curl_easy_setopt(easy_handle, CURLOPT_VERBOSE, 1);   
    curl_easy_setopt(easy_handle, CURLOPT_HEADER, 1);  
    curl_easy_setopt(easy_handle, CURLOPT_HTTPPOST, formpost);

    res = curl_easy_perform(easy_handle);
    curl_slist_free_all(http_headers);
    curl_formfree(formpost);
    curl_easy_cleanup(easy_handle);
    fclose(fptr);
    curl_global_cleanup();
上一篇下一篇

猜你喜欢

热点阅读