URL处理:解析

import android.net.Uri;

import java.net.URLDecoder;
import java.util.regex.Pattern;

public class Parser {
        protected static final Pattern PAT_QUERY =
            Pattern.compile("\\?(([a-z0-9-._~]|%[0-9a-f]{2}|[!$&'()*+,;=]|[:@]|[/?]|[/#])*)", Pattern.CASE_INSENSITIVE);

    public Parser() {
    }

    public static String getQueryParameter(String url, String key){

        try {
            int qsi = url.indexOf('?', url.indexOf(':'));
            String query = url.substring(qsi + 1);

            final String encodedKey = Uri.encode(key, null);
            final int length = query.length();
            int start = 0;
            do {
                int nextAmpersand = query.indexOf('&', start);
                int end = nextAmpersand != -1 ? nextAmpersand : length;

                int separator = query.indexOf('=', start);
                if (separator > end || separator == -1) {
                    separator = end;
                }

                if (separator - start == encodedKey.length()
                        && query.regionMatches(start, encodedKey, 0, encodedKey.length())) {
                    if (separator == end) {
                        return "";
                    } else {
                        String encodedValue = query.substring(separator + 1, end);
                        return URLDecoder.decode(encodedValue, "utf-8");
                    }
                }

                // Move start to end of name.
                if (nextAmpersand != -1) {
                    start = nextAmpersand + 1;
                } else {
                    break;
                }
            } while (true);

        }catch (Exception e){

        }

        return null;
    }

    public class Components {
        public String scheme_ = null;
        public String userinfo_ = null;
        public String host_ = null;
        public HostType hostType_ = null;
        public Integer port_ = null;
        public String[] path_ = null;
        public Boolean pathAbsolute_ = null;
        public String query_ = null;
        public String fragment_ = null;
    }

    public enum HostType {
        IPV4, IPV6, IPVFUTURE, REG_NAME
    }
}
打赏