前回OpenSSLをビルドしてlibssl.libとlibcrypto.libを作ったので、それらをリンクしたlibcurl.libをビルドする。
前々回のlibcurlのビルドで、プロジェクト設定を以下のように変更する。
まずLIB Release - LIB OpenSSL を選択。
libssl.lib ; libcrypto.libを依存ファイルとして設定。それらがあるライブラリディレクトリを指定。
opensslのincludeディレクトリを指定。
以上でlibcurlをビルドできたので、これを使ったプログラムをビルドしてみる。
curlのlibファイルのディレクトリに加え、opensslのlibファイルのディレクトリも追加してビルドする。
以下の二つを追加ライブラリディレクトリに設定
以下から、cacert.pemをダウンロードして、カレントディレクトリに配置する。
https://curl.se/docs/caextract.html
#include <iostream> #define CURL_STATICLIB #include<curl/curl.h> // OS提供 #pragma comment(lib, "CRYPT32.LIB") #pragma comment(lib, "wldap32.lib" ) #pragma comment(lib, "Ws2_32.lib") // 作成したlibcurl #pragma comment(lib,"libcurl.lib") // 作成したopenssl #pragma comment(lib,"libssl.lib") #pragma comment(lib,"libcrypto.lib") size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } bool PerformHttpsRequest(const std::string& url, std::string& response) { CURL* curl; CURLcode res; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (!curl) { std::cerr << "Error: Failed to initialize libcurl." << std::endl; return false; } curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); /// ///////// // 相手がhttpsの場合、以下五行を入れないと SSL peer certificate or SSH remote key was not OK というエラーが出る。
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 1); curl_easy_setopt(curl, CURLOPT_CAINFO, R"(.\cacert.pem)"); curl_easy_setopt(curl, CURLOPT_CAPATH, R"(.\cacert.pem)"); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1L);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "Error: curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
curl_easy_cleanup(curl);
curl_global_cleanup();
return false;
}
curl_easy_cleanup(curl);
curl_global_cleanup();
return true;
}
int main() {
std::string url = "https://suzulang.com/";
std::string response;
if (PerformHttpsRequest(url, response)) {
std::cout << "Response from " << url << ":" << std::endl;
std::cout << response << std::endl;
}
return 0;
}