2014年3月20日 星期四

VC++ cURL POST程式範例

官方網站:http://curl.haxx.se/
官方下載頁:http://curl.haxx.se/download.html (libcurl-7.19.3-win32-ssl-msvc.zip)

將include/curl放到VC的include目錄下
將lib、dll放到程式目錄下

cURL C++ 用法:
#include "stdafx.h"
#include <curl\curl.h>
#pragma comment(lib, "curllib.lib")

size_t write_header(void *ptr, size_t size, size_t count, void *stream)
{
    printf("Value: %s\n", ptr);
    return count*size;
}

void login(char *email, char *password) {
    CURL *curl;
    CURLcode res;

    //email=test@gmail.com&password=abcd1234
    char str[150] = "email=";
    strcat(str, email);
    strcat(str, "&password=");
    strcat(str, password);

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:1337/login"); //登入API的URL
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, str);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_header);
 
        res = curl_easy_perform(curl);
        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    return;
}

int main(int argc, char* argv[])
{
    login("test@gmail.com", "abcd1234");
    system("pause");
    return 0;
}

另有C#使用WebRequest版本:
http://codeboxy.blogspot.com/2014/03/c-post-using-webrequest.html

沒有留言:

張貼留言