使用libcurl庫(kù)可實(shí)現(xiàn)C 中的HTTP GET請(qǐng)求,需先安裝并鏈接libcurl,然后通過(guò)curl_easy_init初始化、設(shè)置URL和回調(diào)函數(shù)接收數(shù)據(jù)、執(zhí)行請(qǐng)求并清理資源,最后編譯時(shí)鏈接-lcurl。
Making an HTTP GET request in C requires using a networking library, since the standard C library doesn't include built-in support for HTTP. One of the most common and practical ways is using libcurl, a powerful, cross-platform library for handling URLs and HTTP requests.
Install and Link libcurl
Before writing code, make sure libcurl is installed on your system.
-
Ubuntu/Debian:
sudo apt install libcurl4-openssl-dev
-
macOS (with Homebrew):
brew install curl
- Windows: Use vcpkg or download prebuilt binaries.
When compiling, link against the curl library using -lcurl
.
Write the HTTP GET Request Code
Here’s a simple example that performs an HTTP GET request and prints the response body:
#include <iostream> #include <string> #include <curl/curl.h> <p>// Callback function to handle data received size_t WriteCallback(void<em> contents, size_t size, size_t nmemb, std::string</em> output) { size_t totalSize = size <em> nmemb; output->append((char</em>)contents, totalSize); return totalSize; }</p><p>int main() { CURL* curl; CURLcode res; std::string readBuffer;</p><pre class="brush:php;toolbar:false"><code>curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/get"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); res = curl_easy_perform(curl); if (res == CURLE_OK) { std::cout << "Response:\n" << readBuffer << std::endl; } else { std::cerr << "Request failed: " << curl_easy_strerror(res) << std::endl; } curl_easy_cleanup(curl); } else { std::cerr << "Could not initialize curl." << std::endl; } return 0;
}
Compile and Run
Save the code to a file (e.g., get_request.cpp
) and compile it:
g get_request.cpp -o get_request -lcurl
Then run:
./get_request
Handle Errors and Timeouts (Optional)
You can improve reliability by setting timeouts and checking connection issues:
- Add
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
for a 10-second timeout. - Use
CURLOPT_USERAGENT
to set a user agent if required. - Enable SSL verification in production with proper CA bundle paths if needed.
Basically just initialize curl, set options, perform the request, and clean up. The callback collects incoming data. With libcurl, it's straightforward once set up.
以上是如何用 C 語(yǔ)言發(fā)出 HTTP GET 請(qǐng)求的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Stock Market GPT
人工智能驅(qū)動(dòng)投資研究,做出更明智的決策

熱門(mén)文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)代碼編輯軟件(SublimeText3)

自定義分配器可用于控制C 容器的內(nèi)存分配行為,1.示例中的LoggingAllocator通過(guò)重載allocate、deallocate、construct和destroy方法實(shí)現(xiàn)內(nèi)存操作日志記錄;2.分配器需定義value_type和rebind模板,以滿足STL容器類(lèi)型轉(zhuǎn)換需求;3.分配器構(gòu)造與拷貝時(shí)觸發(fā)日志輸出,便于追蹤生命周期;4.實(shí)際應(yīng)用包括內(nèi)存池、共享內(nèi)存、調(diào)試工具和嵌入式系統(tǒng);5.C 17起construct和destroy可由std::allocator_traits默認(rèn)處理

使用std::system()函數(shù)可執(zhí)行系統(tǒng)命令,需包含頭文件,傳入C風(fēng)格字符串命令,如std::system("ls-l"),返回值為-1表示命令處理器不可用。

創(chuàng)建項(xiàng)目目錄結(jié)構(gòu),包含CMakeLists.txt、src/和include/;2.編寫(xiě)CMakeLists.txt,指定CMake版本、項(xiàng)目名稱(chēng)、C 標(biāo)準(zhǔn)并添加可執(zhí)行文件;3.使用mkdirbuild進(jìn)入目錄并運(yùn)行cmake..和cmake--build.進(jìn)行編譯;4.通過(guò)add_executable添加多個(gè)源文件,用target_include_directories包含頭文件路徑;5.使用find_package查找外部庫(kù)并用target_link_libraries鏈接;6.通過(guò)tar

C 的stack是STL中的容器適配器,遵循后進(jìn)先出原則,需包含頭文件;通過(guò)push添加元素,pop移除頂部元素,top訪問(wèn)棧頂,操作前應(yīng)檢查是否為空,常用于表達(dá)式求值、回溯等場(chǎng)景。

Theautokeywordletsthecompilerdeducevariabletypesfrominitializers,reducingverbosityandimprovingmaintainability.Itsimplifiescodewithcomplextypeslikeiteratorsandlambdas,supportsreferencesandconstqualifierstoavoidunnecessarycopies,andadaptsautomaticallyw

答案是定義包含必要類(lèi)型別名和操作的類(lèi)。首先設(shè)置value_type、reference、pointer、difference_type和iterator_category,然后實(shí)現(xiàn)解引用、遞增及比較操作,最后在容器中提供begin()和end()方法以返回迭代器實(shí)例,使其兼容STL算法和范圍for循環(huán)。

AstaticVariableInc witherinsitvaluebetwunctioncallsandisinitializedonce.2.Inideafunction,itpreservesstataTateAcrossCalls,siseascountingIterations.3.inaclass,itissharedamondamongallinStancessandMustancessandMustancessandMustbedIendEctIndEtheClastoAvoVovoiDlinkingErrors.4.StaticvariA.StaticvAriA.StaticVariA.StaticVariA

使用std::ifstream和std::istreambuf_iterator可高效讀取文件全部?jī)?nèi)容到字符串,包括空格和換行,適用于中等大小文本文件。
