C++解析url地址成为prot://host:port/path?query[param]

2019-06-11 10:57:02 浏览数 (1)

一点都不复杂,按照url格式分析就可以了。

代码语言:javascript复制
bool httpclient::urlparse(std::string urlin, urlitem & out) {
    bool ret = false;
    int i = 0;
    if (_stricmp(urlin.substr(0, 4).c_str(), "http") != 0)
        return false;
    int lastpos = 0;
    int pos = 0;
    std::string childs[10];
    std::string temp;
    int idx = 0;
    out.url = urlin;
    // 查找‘?’
    out.fullpath = urlin;
    pos = urlin.find('?', 0);
    if (pos >= 0) {
        out.fullpath = urlin.substr(0, pos);
        out.query = urlin.substr(pos 1);
    }
    // 分析query以 & 分割参数对,以=分割 k-v
    lastpos = 0;
    for (i = 0; i < out.query.length(); i  ) {
        if (out.query[i] == '&') {
            temp = out.query.substr(lastpos, i - lastpos);
            pos = temp.find('=', 0);
            if (pos >= 0) {
                out.param[temp.substr(0, pos)] = temp.substr(pos 1);
            }
            lastpos = i   1;
        }
    }
    temp = out.query.substr(lastpos);
    pos = temp.find('=', 0);
    if (pos >= 0) {
        out.param[temp.substr(0, pos)] = temp.substr(pos   1);
    }
    lastpos = 0;
    idx = 0;
    for (i = 0; i < out.fullpath.length(); i  ) {
        if (out.fullpath[i] == ':') {
            childs[idx] = out.fullpath.substr(lastpos, i - lastpos);
            lastpos = i   1;
            idx  ;
            break;
        }
    }
    out.prot = childs[0];
    out.port = 80;
    std::string fullpath = out.fullpath.substr(out.prot.length()   3);
    pos = fullpath.find('/');
    if (pos >= 0) {
        out.host = fullpath.substr(0, pos);
        out.path = fullpath.substr(pos);
    }else if (pos = fullpath.find('\') >= 0) {
        out.host = fullpath.substr(0, pos);
        out.path = fullpath.substr(pos);
    }
    pos = out.host.find(':');
    if (pos >= 0) {
        out.port = atoi(out.host.substr(pos 1).c_str());
        out.host = out.host.substr(0, pos);
    }
    pos = out.path.rfind('/');
    if (pos >= 0) {
        out.file = out.path.substr(pos   1);
    }else if (pos = out.path.rfind('\') >= 0) {
        out.file = out.path.substr(pos   1);
    }
    struct hostent *hptr;
    char **pptr;
    if ((hptr = gethostbyname(out.host.c_str())) != nullptr) {
        if (hptr->h_name != nullptr)
            out.officalhost = hptr->h_name;
        for (pptr = hptr->h_aliases; *pptr != NULL; pptr  )
            out.aliases.push_back(*pptr);
        switch (hptr->h_addrtype){
        case AF_INET:
        //case AF_INET6:
            pptr = hptr->h_addr_list;
            for (; *pptr != NULL; pptr  ) {
                out.ip.push_back(inet_ntoa(*((in_addr *)*pptr)));
            }
            break;
        default:
            break;
        }
    }

    return ret;
}

结果如图:

val.jpg

url

0 人点赞