🔥

【C 言語】cURL で HTTP リクエスト

2024/04/18に公開

公式サイトの sample.c をそのまま利用させてもらう

#include <stdio.h>
#include <curl/curl.h>

// https://curl.se/libcurl/c/simple.html

int main(void)
{
  CURL *curl;
  CURLcode res;
 
  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");

    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
 
    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);
  }
  return 0;
}

コンパイルと実行は次のとおり

zig run test.c -l c -l curl
clang run test.c -l curl -o test
./test

Debian の場合、あらかじめ次のパッケージをインストールしておく

sudo apt install libcurl4-openssl-dev 

Discussion