在C++跨平台上解析url的简单方法?

And*_*ell 67 c++ url uri

我需要解析一个URL,以便在我用C++编写的应用程序中获取协议,主机,路径和查询.该应用程序旨在跨平台.我很惊讶我在boostPOCO库中找不到任何这样的功能.这是显而易见的我不看的地方吗?关于适当的开源库的任何建议?或者这是我必须自己做的事情?它并不是非常复杂,但似乎是一项常见的任务,我很惊讶没有一个共同的解决方案.

Dea*_*ael 29

有一个建议用于包含Boost的库,允许您轻松解析HTTP URI.它使用Boost.Spirit,也在Boost软件许可下发布.该库是cpp-netlib,您可以在http://cpp-netlib.github.com/找到该文档- 您可以从http://github.com/cpp-netlib/cpp-netlib下载最新版本/下载.

你要使用的相关类型boost::network::http::uri,并记录在这里.

  • 由于过时原因添加注释:由于 Boost 弃用了 get_io_service,该库在 2020 年不再按预期整体使用最新版本的 Boost 进行编译。但是,您仍然可以从框架中提取相关功能,因为它是独立的并且不依赖于库的这些部分。 (2认同)

wil*_*ell 21

非常抱歉,忍不住了.:■

url.hh

#ifndef URL_HH_
#define URL_HH_    
#include <string>
struct url {
    url(const std::string& url_s); // omitted copy, ==, accessors, ...
private:
    void parse(const std::string& url_s);
private:
    std::string protocol_, host_, path_, query_;
};
#endif /* URL_HH_ */
Run Code Online (Sandbox Code Playgroud)

url.cc

#include "url.hh"
#include <string>
#include <algorithm>
#include <cctype>
#include <functional>
using namespace std;

// ctors, copy, equality, ...

void url::parse(const string& url_s)
{
    const string prot_end("://");
    string::const_iterator prot_i = search(url_s.begin(), url_s.end(),
                                           prot_end.begin(), prot_end.end());
    protocol_.reserve(distance(url_s.begin(), prot_i));
    transform(url_s.begin(), prot_i,
              back_inserter(protocol_),
              ptr_fun<int,int>(tolower)); // protocol is icase
    if( prot_i == url_s.end() )
        return;
    advance(prot_i, prot_end.length());
    string::const_iterator path_i = find(prot_i, url_s.end(), '/');
    host_.reserve(distance(prot_i, path_i));
    transform(prot_i, path_i,
              back_inserter(host_),
              ptr_fun<int,int>(tolower)); // host is icase
    string::const_iterator query_i = find(path_i, url_s.end(), '?');
    path_.assign(path_i, query_i);
    if( query_i != url_s.end() )
        ++query_i;
    query_.assign(query_i, url_s.end());
}
Run Code Online (Sandbox Code Playgroud)

main.cc

// ...
    url u("HTTP://stackoverflow.com/questions/2616011/parse-a.py?url=1");
    cout << u.protocol() << '\t' << u.host() << ...
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是事情是这样的,恰恰相反,我同意Billy ONeal并删除所有`using namespace'.如果你真的重复了一个符号,你总是可以使用`std :: string;`但是我更喜欢使用命名空间限定条件,让那些可怜的老人更容易理解这个符号的来源. (13认同)
  • 除了example.com:port/pathname之外,还有许多URI/URL表单不受支持.例如http:/ pathname,更重要的是http:// username:password@example.com/pathname#section - 所有组合都列在http://www.ietf.org/rfc/rfc2396.txt中 - 它们显示了跟随正则表达式:^(([^:/?#] +):)?(//([^ /?#]*))?([^?#]*)(\?([^#]*) )?(#(.*))? (7认同)
  • @Billy我总是将命名空间`std`带入我的编译单元(而不是标题!).我认为它非常好,而且我觉得整个地方都有'std ::'比引入名称空间更容易造成污染和眼睛疲劳. (4认同)
  • 小吹毛求疵:你不需要在这里使用 ptr_fun,如果你这样做了,你需要`#include &lt;functional&gt;`。(您可能也不应该“使用命名空间 std”,但我假设这不适用于生产代码) (2认同)

Tom*_*Tom 20

上面的Wstring版本,添加了我需要的其他字段.绝对可以精炼,但足够我的目的.

#include <string>
#include <algorithm>    // find

struct Uri
{
public:
std::wstring QueryString, Path, Protocol, Host, Port;

static Uri Parse(const std::wstring &uri)
{
    Uri result;

    typedef std::wstring::const_iterator iterator_t;

    if (uri.length() == 0)
        return result;

    iterator_t uriEnd = uri.end();

    // get query start
    iterator_t queryStart = std::find(uri.begin(), uriEnd, L'?');

    // protocol
    iterator_t protocolStart = uri.begin();
    iterator_t protocolEnd = std::find(protocolStart, uriEnd, L':');            //"://");

    if (protocolEnd != uriEnd)
    {
        std::wstring prot = &*(protocolEnd);
        if ((prot.length() > 3) && (prot.substr(0, 3) == L"://"))
        {
            result.Protocol = std::wstring(protocolStart, protocolEnd);
            protocolEnd += 3;   //      ://
        }
        else
            protocolEnd = uri.begin();  // no protocol
    }
    else
        protocolEnd = uri.begin();  // no protocol

    // host
    iterator_t hostStart = protocolEnd;
    iterator_t pathStart = std::find(hostStart, uriEnd, L'/');  // get pathStart

    iterator_t hostEnd = std::find(protocolEnd, 
        (pathStart != uriEnd) ? pathStart : queryStart,
        L':');  // check for port

    result.Host = std::wstring(hostStart, hostEnd);

    // port
    if ((hostEnd != uriEnd) && ((&*(hostEnd))[0] == L':'))  // we have a port
    {
        hostEnd++;
        iterator_t portEnd = (pathStart != uriEnd) ? pathStart : queryStart;
        result.Port = std::wstring(hostEnd, portEnd);
    }

    // path
    if (pathStart != uriEnd)
        result.Path = std::wstring(pathStart, queryStart);

    // query
    if (queryStart != uriEnd)
        result.QueryString = std::wstring(queryStart, uri.end());

    return result;

}   // Parse
};  // uri
Run Code Online (Sandbox Code Playgroud)

测试/用法

Uri u0 = Uri::Parse(L"http://localhost:80/foo.html?&q=1:2:3");
Uri u1 = Uri::Parse(L"https://localhost:80/foo.html?&q=1");
Uri u2 = Uri::Parse(L"localhost/foo");
Uri u3 = Uri::Parse(L"https://localhost/foo");
Uri u4 = Uri::Parse(L"localhost:8080");
Uri u5 = Uri::Parse(L"localhost?&foo=1");
Uri u6 = Uri::Parse(L"localhost?&foo=1:2:3");

u0.QueryString, u0.Path, u0.Protocol, u0.Host, u0.Port....
Run Code Online (Sandbox Code Playgroud)


Ell*_*ron 12

为了完整起见,有一个用C语言写的,你可以使用(有点包装,毫无疑问):http://uriparser.sourceforge.net/

[符合RFC并支持Unicode]


这是一个非常基本的包装器,我一直用来简单地抓取解析的结果.

#include <string>
#include <uriparser/Uri.h>


namespace uriparser
{
    class Uri //: boost::noncopyable
    {
        public:
            Uri(std::string uri)
                : uri_(uri)
            {
                UriParserStateA state_;
                state_.uri = &uriParse_;
                isValid_   = uriParseUriA(&state_, uri_.c_str()) == URI_SUCCESS;
            }

            ~Uri() { uriFreeUriMembersA(&uriParse_); }

            bool isValid() const { return isValid_; }

            std::string scheme()   const { return fromRange(uriParse_.scheme); }
            std::string host()     const { return fromRange(uriParse_.hostText); }
            std::string port()     const { return fromRange(uriParse_.portText); }
            std::string path()     const { return fromList(uriParse_.pathHead, "/"); }
            std::string query()    const { return fromRange(uriParse_.query); }
            std::string fragment() const { return fromRange(uriParse_.fragment); }

        private:
            std::string uri_;
            UriUriA     uriParse_;
            bool        isValid_;

            std::string fromRange(const UriTextRangeA & rng) const
            {
                return std::string(rng.first, rng.afterLast);
            }

            std::string fromList(UriPathSegmentA * xs, const std::string & delim) const
            {
                UriPathSegmentStructA * head(xs);
                std::string accum;

                while (head)
                {
                    accum += delim + fromRange(head->text);
                    head = head->next;
                }

                return accum;
            }
    };
}
Run Code Online (Sandbox Code Playgroud)

  • +1,我最终克隆了你的URL解析器lib github.更好的是不必全力提升...... (3认同)

Mic*_*ell 8

POCO的URI类可以为您解析URL.以下示例是POCO URI和UUID幻灯片中的缩写版本:

#include "Poco/URI.h"
#include <iostream>

int main(int argc, char** argv)
{
    Poco::URI uri1("http://www.appinf.com:88/sample?example-query#frag");

    std::string scheme(uri1.getScheme()); // "http"
    std::string auth(uri1.getAuthority()); // "www.appinf.com:88"
    std::string host(uri1.getHost()); // "www.appinf.com"
    unsigned short port = uri1.getPort(); // 88
    std::string path(uri1.getPath()); // "/sample"
    std::string query(uri1.getQuery()); // "example-query"
    std::string frag(uri1.getFragment()); // "frag"
    std::string pathEtc(uri1.getPathEtc()); // "/sample?example-query#frag"

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*hen 5

QT 有QUrl来解决这个问题。GNOME在libsoup中有SoupURI,您可能会发现它更轻量。


小智 5

Poco库现在有一个用于剖析URI并反馈主机,路径段和查询字符串等的类.

https://pocoproject.org/pro/docs/Poco.URI.html


vel*_*row 5

//sudo apt-get install libboost-all-dev; #install boost
//g++ urlregex.cpp -lboost_regex; #compile
#include <string>
#include <iostream>
#include <boost/regex.hpp>

using namespace std;

int main(int argc, char* argv[])
{
    string url="https://www.google.com:443/webhp?gws_rd=ssl#q=cpp";
    boost::regex ex("(http|https)://([^/ :]+):?([^/ ]*)(/?[^ #?]*)\\x3f?([^ #]*)#?([^ ]*)");
    boost::cmatch what;
    if(regex_match(url.c_str(), what, ex)) 
    {
        cout << "protocol: " << string(what[1].first, what[1].second) << endl;
        cout << "domain:   " << string(what[2].first, what[2].second) << endl;
        cout << "port:     " << string(what[3].first, what[3].second) << endl;
        cout << "path:     " << string(what[4].first, what[4].second) << endl;
        cout << "query:    " << string(what[5].first, what[5].second) << endl;
        cout << "fragment: " << string(what[6].first, what[6].second) << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

Facebook 的Folly库可以轻松为您完成这项工作。只需使用Uri类:

#include <folly/Uri.h>

int main() {
    folly::Uri folly("https://code.facebook.com/posts/177011135812493/");

    folly.scheme(); // https
    folly.host();   // code.facebook.com
    folly.path();   // posts/177011135812493/
}
Run Code Online (Sandbox Code Playgroud)