4
5

More than 1 year has passed since last update.

C++ の http クライアントの使い方 (Get)

Last updated at Posted at 2018-05-26

Ubuntu 22.10 でのライブラリーのインストール

sudo apt install libcurl4-openssl-dev
http_get.cpp
// --------------------------------------------------------------------
/*
	http_get.cpp

					May/27/2018

*/
// --------------------------------------------------------------------
#include	<string>
#include	<iostream>

#include	<curl/curl.h>

using namespace std;

// --------------------------------------------------------------------
size_t callBackFunk(char* ptr, size_t size, size_t nmemb, string* stream)
{
	int realsize = size * nmemb;
	stream->append(ptr, realsize);
	return realsize;
}

// --------------------------------------------------------------------
string url_get_proc (const char url[])
{
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();
	string chunk;

	if (curl)
		{
		curl_easy_setopt(curl, CURLOPT_URL, url);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callBackFunk);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (string*)&chunk);
		curl_easy_setopt(curl, CURLOPT_PROXY, "");
		res = curl_easy_perform(curl);
		curl_easy_cleanup(curl);
		}
	if (res != CURLE_OK) {
		cout << "curl error" << endl;
		exit (1);
	}

	return chunk;
}

// --------------------------------------------------------------------
int main (int argc,char *argv[])
{
	cerr << "*** 開始 ***\n";

	char url_target[] = "https://httpbin.org/get";

	string str_out = url_get_proc (url_target);

	cout << str_out << "\n";

	cerr << "*** 終了 ***\n";

	return 0;
}

// --------------------------------------------------------------------
Makefile
http_get.exe: http_get.cpp
	clang++ -o http_get http_get.cpp -lcurl
clean:
	rm -f http_get

実行結果

*** 開始 ***
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Host": "httpbin.org", 
    "X-Amzn-Trace-Id": "Root=1-5f253e0e-8f5d92c07e9684c0788f1b40"
  }, 
  "origin": "219.126.139.62", 
  "url": "https://httpbin.org/get"
}

*** 終了 ***

次のバージョンで確認しました。

$ clang++ --version
Ubuntu clang version 15.0.2-1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

関連ページ
C++ の http クライアントの使い方 (Post)

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5