在C语言中发送HTTP请求,通常使用libcurl库,这是一个广泛使用的库,用于在C/C++应用程序中发送HTTP请求。以下是一个简单的例子,展示了如何使用libcurl发送一个HTTP GET请求。
确保你的系统中已经安装了libcurl库。安装方法取决于你的操作系统。例如,在Ubuntu上,你可以使用以下命令安装:
```sh
sudo apt-get install libcurl4-openssl-dev
```
以下是一个使用libcurl发送HTTP GET请求的示例代码:
```c
include
include
int main(void)
{
CURL curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); // 设置请求的URL
// 设置请求类型为GET
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
// 执行HTTP请求
res = curl_easy_perform(curl);
// 检查错误
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %sn",
curl_easy_strerror(res));
// 清理
curl_easy_cleanup(curl);