// str_url = https://なURL
// api叩くとjson返すのでpicojson使ってる
picojson::object func_api_req(const CString& str_url) {
// Using MFC WinINet classes
CInternetSession session(_T("My Session"), 1, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_SECURE);
CHttpConnection* pServer = NULL;
CHttpFile* pFile = NULL;
CString strServerName;
INTERNET_PORT nPort;
CString strObject;
DWORD dwServiceType;
// Breaking the URL into its components by using CrackUrl()
if (!AfxParseURL(str_url, dwServiceType, strServerName, strObject, nPort) ||
dwServiceType != INTERNET_SERVICE_HTTP)
{
// URL is malformed. Error handling here.
throw std::runtime_error("Malformed URL");
}
// Opening a connection to the HTTP server
try {
pServer = session.GetHttpConnection(strServerName, nPort);
// Sending a request to the server
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD);
pFile->SendRequest();
}
catch (CInternetException* pEx) {
// エラーメッセージの表示
TCHAR sz[1024];
pEx->GetErrorMessage(sz, 1024);
std::cerr << "Caught a CInternetException: " << sz << std::endl;
// 例外オブジェクトの削除
pEx->Delete();
if (pServer != NULL) delete pServer;
throw std::runtime_error("HTTP request failed");
}
catch (...) {
if (pServer != NULL) delete pServer;
throw;
}
// Insert the response processing code here
picojson::object obj;
return obj;
}
このコードでは CInternetSession オブジェクトの作成時に INTERNET_FLAG_SECURE フラグを使用して、HTTPS接続を有効にしています。
同様に OpenRequest() 関数も INTERNET_FLAG_SECURE フラグを使用してHTTPS接続を有効にしています。
ただし、上記のコードはHTTPS接続の基本的な設定のみを含んでおり、詳細な証明書の検証やエラーハンドリングは実装されていません。
そのため、本番環境での使用には、適切なエラーハンドリングと証明書の検証を追加することを強く推奨します。