C++使用curl庫進行http請求的方法詳解
實現(xiàn)代碼
#include <iostream> #include <string> #include <curl/curl.h> #include <ctime> #include <iomanip> size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) { size_t totalSize = size * nmemb; output->append(static_cast<char*>(contents), totalSize); return totalSize; } // 將日期字符串轉(zhuǎn)換為指定格式 std::string formatDateString(const std::string& dateString) { std::tm t; std::istringstream iss(dateString); // 解析日期字符串 iss >> std::get_time(&t, "%a, %d %b %Y %H:%M:%S %Z"); if (iss.fail()) { return ""; } std::ostringstream oss; // 格式化日期 oss << std::put_time(&t, "%m%d%H%M%Y.%S"); return oss.str(); } int main() { CURL* curl; CURLcode res; std::string responseHeaders; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://your-backend-server/current-time"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeaders); curl_easy_setopt(curl, CURLOPT_HEADER, 1L); res = curl_easy_perform(curl); if (res != CURLE_OK) { std::cerr << "Failed to perform request: " << curl_easy_strerror(res) << std::endl; } else { std::string dateHeader = "Date: "; size_t startPos = responseHeaders.find(dateHeader); if (startPos != std::string::npos) { startPos += dateHeader.length(); size_t endPos = responseHeaders.find("\r ", startPos); std::string dateString = responseHeaders.substr(startPos, endPos - startPos); std::string formattedDate = formatDateString(dateString); if (!formattedDate.empty()) { std::cout << "Formatted date: " << formattedDate << std::endl; } else { std::cerr << "Failed to format date string." << std::endl; } } else { std::cerr << "Failed to extract server time from response headers." << std::endl; } } curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
formatdatestring方法會將時間格式化為指定的格式,但是如果頭部信息返回的時間如果不是北京時間,則可以修改方法修改為北京時間,如下:
// 將日期字符串轉(zhuǎn)換為指定格式(北京時間) std::string formatDateString(const std::string& dateString) { std::tm t; std::istringstream iss(dateString); // 解析日期字符串 iss >> std::get_time(&t, "%a, %d %b %Y %H:%M:%S %Z"); if (iss.fail()) { return ""; } // 將 tm 結(jié)構(gòu)轉(zhuǎn)換為系統(tǒng)時鐘的時間點 std::chrono::system_clock::time_point tp = std::chrono::system_clock::from_time_t(std::mktime(&t)); // 將時間點轉(zhuǎn)換為北京時間 std::chrono::hours offset(8); // 北京時間偏移量為+8小時 tp += offset; // 轉(zhuǎn)換為本地時間 std::time_t tt = std::chrono::system_clock::to_time_t(tp); t = *std::localtime(&tt); std::ostringstream oss; // 格式化日期 oss << std::put_time(&t, "%m%d%H%M%Y.%S"); return oss.str(); } int main() { // ... }
知識補充
可能有小伙伴對于curl庫不太熟悉,下面小編為大家簡單介紹一下curl庫的使用,需要的可以參考一下
關于Curl庫
curl 是一個利用URL語法在命令行方式下工作的文件傳輸工具。它支持很多協(xié)議:FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP。curl不但提供了一個可執(zhí)行的工具庫,還提供了供程序開發(fā)的libcurl庫,該庫使用c語言編寫,支持跨平臺。
編譯安裝
編譯curl庫很簡單的,找到自己對應的VS目錄,然后打開工程,選擇所需要的版本即可編譯。我使用的是VS2010的靜態(tài)庫版本,因此選擇VC10目錄->LIB Debug版本,然后編譯,編譯后生成libcurld.lib和對應的調(diào)試信息文件libcurld.pdb,這樣我們開發(fā)調(diào)試的時候只需要把該庫文件和curl庫的頭文件文件夾curl加到我們的工程里面就可以使用curl庫給我們提供的功能了。不過需要注意的是,因為CURL的特殊性,需要預定義一些宏和添加特定的依賴庫,如下所示:
// 需要定義的宏,要不然會提示找不到某些函數(shù)的定義 #define BUILDING_LIBCURL //#define HTTP_ONLY // 依賴庫 #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "wldap32.lib") #pragma comment(lib, "libcurld.lib")
主要函數(shù)列表
1.全局初始化
CURLcode curl_global_init(long flags);
描述: 這個函數(shù)只能用一次(其實在調(diào)用curl_global_cleanup 函數(shù)后仍然可再用),如果這個函數(shù)在curl_easy_init函數(shù)調(diào)用時還沒調(diào)用,它講由libcurl庫自動完成。
參數(shù):flags
CURL_GLOBAL_ALL //初始化所有的可能的調(diào)用。
CURL_GLOBAL_SSL //初始化支持 安全套接字層。
CURL_GLOBAL_WIN32 //初始化win32套接字庫。
CURL_GLOBAL_NOTHING //沒有額外的初始化
2.全局清理
void curl_global_cleanup(void);
描述:在結(jié)束libcurl使用的時候,用來對curl_global_init做的工作清理。類似于close的函數(shù)。
3.獲取Curl版本庫
char *curl_version();
描述: 打印當前l(fā)ibcurl庫的版本。
4.初始化curl會話
CURL *curl_easy_init();
描述: curl_easy_init用來初始化一個CURL的指針(有些像返回FILE類型的指針一樣),相應的在調(diào)用結(jié)束時要用curl_easy_cleanup函數(shù)清理。一般curl_easy_init意味著一個會話的開始,它的返回值一般都用在easy系列的函數(shù)。
5.清理cur會話
void curl_easy_cleanup(CURL *handle);
描述: 這個調(diào)用用來結(jié)束一個會話,與curl_easy_init配合著用。
參數(shù): CURL類型的指針。
6.設置curl會話參數(shù)
CURLcode curl_easy_setopt(CURL *handle, CURLoption option, parameter);
描述: 這個函數(shù)最重要了,幾乎所有的curl程序都要頻繁的使用它,用來設置參數(shù)。它告訴curl庫,程序?qū)⒂腥绾蔚男袨?,比如要查看一個網(wǎng)頁的html代碼等。
- 參數(shù)handle:CURL類型的指針
- 參數(shù)option:各種CURLoption類型的選項。(都在curl.h庫里有定義,man 也可以查看到)
- 參數(shù)parameter: 這個參數(shù)既可以是個函數(shù)的指針,也可以是某個對象的指針,也可以是個long型的變量,它用什么這取決于第二個參數(shù)。
7.執(zhí)行curl會話
CURLcode curl_easy_perform(CURL *handle);
描述:這個函數(shù)在初始化CURL類型的指針以及curl_easy_setopt完成后調(diào)用,就像字面的意思所說perform就像是個舞臺,讓我們設置的option運作起來,執(zhí)行curl所設置的動作。
到此這篇關于C++使用curl庫進行http請求的方法詳解的文章就介紹到這了,更多相關C++ curl進行http請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!