原文鏈接:http://www.javashuo.com/article/p-wikhpqqc-dd.htmlhtml
CommonTools.hios
* CommonTools.h
*
* Created on: 2018年8月2日
* Author: didi
*/
#include <iostream>
#include <curl/curl.h>
#include "zlib.h" #include <vector> #include <string> #include <unistd.h> #include <memory.h> #include <json/json.h> #include <sstream> using namespace std; class CommonTools{ public: CommonTools(); ~CommonTools(); public: static size_t receive_data(void *contents, size_t size, size_t nmemb, void *stream); // HTTP 下載文件的回掉函數 static size_t writedata2file(void *ptr, size_t size, size_t nmemb, FILE *stream); // 文件下載接口 static int download_file(const char* url, const char outfilename[FILENAME_MAX]); // http get 請求 static CURLcode HttpGet(const std::string & strUrl, std::string & strResponse,int nTimeout); // htpp post 請求 static CURLcode HttpPost(const std::string & strUrl, std::string szJson,std::string & strResponse,int nTimeout); }
CommonTools.cppjson
using namespace std; size_t CommonTools::receive_data(void *contents, size_t size, size_t nmemb, void *stream){ string *str = (string*)stream; (*str).append((char*)contents, size*nmemb); return size * nmemb; } size_t CommonTools::writedata2file(void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t written = fwrite(ptr, size, nmemb, stream); return written; } int CommonTools::download_file(const char* url, const char outfilename[FILENAME_MAX]){ CURL *curl; FILE *fp; CURLcode res; /* 調用curl_global_init()初始化libcurl */ res = curl_global_init(CURL_GLOBAL_ALL); if (CURLE_OK != res) { printf("init libcurl failed."); curl_global_cleanup(); return -1; } /* 調用curl_easy_init()函數獲得 easy interface型指針 */ curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); /* 調用curl_easy_setopt()設置傳輸選項 */ res = curl_easy_setopt(curl, CURLOPT_URL, url); if (res != CURLE_OK) { fclose(fp); curl_easy_cleanup(curl); return -1; } /* 根據curl_easy_setopt()設置的傳輸選項,實現回調函數以完成用戶特定任務 */ res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CommonTools::writedata2file); if (res != CURLE_OK){ fclose(fp); curl_easy_cleanup(curl); return -1; } /* 根據curl_easy_setopt()設置的傳輸選項,實現回調函數以完成用戶特定任務 */ res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); if (res != CURLE_OK) { fclose(fp); curl_easy_cleanup(curl); return -1; } res = curl_easy_perform(curl); // 調用curl_easy_perform()函數完成傳輸任務 fclose(fp); /* Check for errors */ if(res != CURLE_OK){ fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res)); curl_easy_cleanup(curl); return -1; } /* always cleanup */ curl_easy_cleanup(curl); // 調用curl_easy_cleanup()釋放內存 } curl_global_cleanup(); return 0; } CURLcode CommonTools::HttpGet(const std::string & strUrl, std::string & strResponse,int nTimeout){ CURLcode res; CURL* pCURL = curl_easy_init(); if (pCURL == NULL) { return CURLE_FAILED_INIT; } curl_easy_setopt(pCURL, CURLOPT_URL, strUrl.c_str()); //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); curl_easy_setopt(pCURL, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(pCURL, CURLOPT_TIMEOUT, nTimeout); curl_easy_setopt(pCURL, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, CommonTools::receive_data); curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, (void*)&strResponse); res = curl_easy_perform(pCURL); curl_easy_cleanup(pCURL); return res; } CURLcode CommonTools::HttpPost(const std::string & strUrl, std::string szJson,std::string & strResponse,int nTimeout){ CURLcode res; char szJsonData[1024]; memset(szJsonData, 0, sizeof(szJsonData)); strcpy(szJsonData, szJson.c_str()); CURL* pCURL = curl_easy_init(); struct curl_slist* headers = NULL; if (pCURL == NULL) { return CURLE_FAILED_INIT; } CURLcode ret; ret = curl_easy_setopt(pCURL, CURLOPT_URL, strUrl.c_str()); // std::cout << ret << std::endl; ret = curl_easy_setopt(pCURL, CURLOPT_POST, 1L); headers = curl_slist_append(headers,"content-type:application/json"); ret = curl_easy_setopt(pCURL, CURLOPT_HTTPHEADER, headers); ret = curl_easy_setopt(pCURL, CURLOPT_POSTFIELDS, szJsonData); //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); ret = curl_easy_setopt(pCURL, CURLOPT_TIMEOUT, nTimeout); ret = curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, CommonTools::receive_data); ret = curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, (void*)&strResponse); res = curl_easy_perform(pCURL); curl_easy_cleanup(pCURL); return res; }
使用方法服務器
Main.cppapp
string strURL = "http://www.baidu.com"; string strResponse; CURLcode nRes = CommonTools::HttpGet(strURL, strResponse,300); size_t nSrcLength = strResponse.length(); //下載文件 string strURL = "http://www.baidu.com/aaa.dat"; char local_file[50] = {0}; sprintf(local_file,"./pb_%d_%s.dat",1,"aaaa"); int iDownlaod_Success = CommonTools::download_file(url.c_str(),local_file); if(iDownlaod_Success<0){ char download_failure_info[100] ={0}; sprintf(download_failure_info,"download file :%s ,failure,url:",local_file,url); FATAL(download_failure_info); }
1、Post 字符串curl
#include <stdio.h> #include <curl/curl.h> int main(void) { CURL* curl = NULL; CURLcode res; curl = curl_easy_init(); if(curl == NULL) { return CURLE_FAILED_INIT; } struct curl_slist* headerlist = NULL; // 設置表頭,表頭內容可能不一樣 headerlist = curl_slist_append(headerlist, "Content-Type:application/x-www-form-urlencoded"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); // 設置URL curl_easy_setopt(curl, CURLOPT_URL, "http://postit.example.com/moo.cgi"); // 設置參數,好比"ParamName1=ParamName1Content&ParamName2=ParamName2Content&..." curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=daniel&project=curl"); // 設置爲Post curl_easy_setopt(curl, CURLOPT_POST, 1); // 發送 res = curl_easy_perform(curl); if(res != CURLE_OK) { // 獲取詳細錯誤信息 char* szErr = curl_easy_strerror(res); fprintf(stderr, "curl_easy_perform() failed: %s\n", szErr); } // 清空 curl_easy_cleanup(curl); // 釋放表頭 curl_slist_free_all (headerlist); return 0; }
2、Post 文件ide
#include <stdio.h> #include <curl/curl.h> size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid); int main(void) { CURL* curl = NULL; CURLcode res; curl = curl_easy_init(); if(curl == NULL) { return CURLE_FAILED_INIT; } struct curl_slist* headerlist = NULL; struct curl_httppost* formpost = NULL; struct curl_httppost* lastptr = NULL; std::string strResponse; // 回覆 curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "ParamName1", CURLFORM_COPYCONTENTS, "ParamName1Content", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "ParamName2", CURLFORM_COPYCONTENTS, "ParamName2Content", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "ParamName3", CURLFORM_COPYCONTENTS, "ParamName3Content", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "registerImgs", CURLFORM_FILE, "C:/Image.png", CURLFORM_END); // 設置要上傳的文件 // 設置表單參數 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); // 設置表頭,表頭內容可能不一樣 headerlist = curl_slist_append(headerlist, "Content-Type:application/x-www-form-urlencoded"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); // 設置URL curl_easy_setopt(curl, CURLOPT_URL, "http://postit.example.com/moo.cgi"); // 設置參數,好比"ParamName1=ParamName1Content&ParamName2=ParamName2Content&..." curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=daniel&project=curl"); // 設置爲Post curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&strResponse); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); // 發送 res = curl_easy_perform(curl); if(res != CURLE_OK) { // 獲取詳細錯誤信息 char* szErr = curl_easy_strerror(res); fprintf(stderr, "curl_easy_perform() failed: %s\n", szErr); } // 清空 curl_easy_cleanup(curl); // 釋放表單 curl_formfree(formpost); // 釋放表頭 curl_slist_free_all (headerlist); return 0; } size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid) { std::string* str = dynamic_cast<std::string*>((std::string *)lpVoid); if( NULL == str || NULL == buffer ) { return -1; } char* pData = (char*)buffer; str->append(pData, size * nmemb); return nmemb; }