Wie man den Host aus einer URL in C++ mit Boost::URL parst

English Deutsch

Wenn Sie eine URL wie diese haben:

snippet.cpp
std::string myURL = "https://subdomain.example.com/api/test";

können Sie den Hostnamen daraus mit Boost::URL parsen (Sie benötigen mindestens Boost 1.81.0, frühere Boost-Versionen haben kein Boost.URL) mit

snippet2.cpp
boost::urls::url_view url(myURL);
std::string host = url.host();

std::cout << host << std::endl; // Prints "subdomain.example.com"

Vollständiges Beispiel:

urlhost.cpp
#include <string>
#include <iostream>

#include <boost/url.hpp>

int main() {
    std::string myURL = "https://subdomain.example.com/api/test";

    boost::urls::url_view url(myURL);
    std::string host = url.host();

    std::cout << host << std::endl; // Prints "subdomain.example.com"
}

Kompilieren mit

build_urlhost.sh
g++ -o urlhost urlhost.cpp -lboost_url

Check out similar posts by category: Boost, C/C++