1. 程式人生 > >android java 如何判斷一個url地址為有效url

android java 如何判斷一個url地址為有效url

我們在android 和java開發中可能會遇到一個問題,就是判斷使用者輸入的url或者從網頁或其他地方複製來的url是否為一個有效的url,下面是一些方法,供大家參考:

在沒有encode的情況下可以使用下面方法

URI uriObj = new URI(url);

這個方法來進行判定,如果該方法丟擲異常URISyntaxException,那麼就說明這個url不是一個正確的url,不過當遇到一個url地址中包含字串^的時候,也會丟擲異常,可以這個含有^的連結卻是一個有效的地址,比如百度中的某些地址,因此可以通過下面的程式碼進行改進:

URL urlObj = new URL(url);
URI uriObj = new URI(urlObj.getProtocol(), urlObj.getHost(), urlObj.getPath(), urlObj.getQuery(), null);
這兩個方法分別會丟擲MalformedURLException和URISyntaxException.

不過如果你想對一些schemes進行限制,可以加入以下程式碼:

    private static final String acceptableSchemes[] = {
            "http:",
            "https:",
            "file:"
    };

    private static boolean urlHasAcceptableScheme(String url) {
        if (url == null) {
            return false;
        }

        for (int i = 0; i < acceptableSchemes.length; i++) {
            if (url.startsWith(acceptableSchemes[i])) {
                return true;
            }
        }
        return false;
    }

    private String isValidUrl(String incommingString) throws Exception{
        String url = "";
        URL urlObj = new URL(incommingString);
        URI uriObj = new URI(urlObj.getProtocol(), urlObj.getHost(), urlObj.getPath(), urlObj.getQuery(), null);
        String scheme = uriObj.getScheme();
        if (!urlHasAcceptableScheme(incommingString)) {
            if (scheme != null) {
                throw new URISyntaxException("", "");
            }
        }
        //此處需要對url進行賦值操作,例如需要加http://等
        return url;
    }

對於android開發,還可以以這樣處理:
import android.util.Patterns;//android包下的

if (Patterns.WEB_URL.matcher(searchContent).matches()) {
     //符合標準
} else{
     //不符合標準
}

接下來提供一個完整的封裝類,不但提供了對url的校驗,還對url的大部分資訊進行了封裝操作,程式碼如下:


package 隨便寫;

import static android.util.Patterns.GOOD_IRI_CHAR;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebAddress {

    private String mScheme;
    private String mHost;
    private int mPort;
    private String mPath;
    private String mAuthInfo;

    static final int MATCH_GROUP_SCHEME = 1;
    static final int MATCH_GROUP_AUTHORITY = 2;
    static final int MATCH_GROUP_HOST = 3;
    static final int MATCH_GROUP_PORT = 4;
    static final int MATCH_GROUP_PATH = 5;

    /* ENRICO: imported the ParseExeption here */
    public static class ParseException extends RuntimeException {
        public String response;

        ParseException(String response) {
            this.response = response;
        }
    }
//根據正則表示式進行判斷
    static Pattern sAddressPattern = Pattern.compile(
            /* scheme    */ "(?:(http|https|file)\\:\\/\\/)?" +
            /* authority */ "(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?" +
            /* host      */ "([" + GOOD_IRI_CHAR + "%_-][" + GOOD_IRI_CHAR + "%_\\.-]*|\\[[0-9a-fA-F:\\.]+\\])?" +
            /* port      */ "(?:\\:([0-9]*))?" +
            /* path      */ "(\\/?[^#]*)?" +
            /* anchor    */ ".*", Pattern.CASE_INSENSITIVE);

    /** parses given uriString. */
//用法:將需要判斷的url傳入,new WebAddress(address) 如果丟擲異常,則會出現問題
 public WebAddress(String address) throws ParseException {
        if (address == null) {
            throw new NullPointerException();
        }

        // android.util.Log.d(LOGTAG, "WebAddress: " + address);

        mScheme = "";
        mHost = "";
        mPort = -1;
        mPath = "/";
        mAuthInfo = "";

        Matcher m = sAddressPattern.matcher(address);
        String t;
        if (m.matches()) {
            t = m.group(MATCH_GROUP_SCHEME);
            if (t != null) mScheme = t.toLowerCase(Locale.getDefault());
            t = m.group(MATCH_GROUP_AUTHORITY);
            if (t != null) mAuthInfo = t;
            t = m.group(MATCH_GROUP_HOST);
            if (t != null) mHost = t;
            t = m.group(MATCH_GROUP_PORT);
            if (t != null && t.length() > 0) {
                // The ':' character is not returned by the regex.
                try {
                    mPort = Integer.parseInt(t);
                } catch (NumberFormatException ex) {
                    throw new ParseException("Bad port");
                }
            }
            t = m.group(MATCH_GROUP_PATH);
            if (t != null && t.length() > 0) {
                /* handle busted myspace frontpage redirect with
                   missing initial "/" */
                if (t.charAt(0) == '/') {
                    mPath = t;
                } else {
                    mPath = "/" + t;
                }
            }

        } else {
            // nothing found... outa here
            throw new ParseException("Bad address");
        }

        /* Get port from scheme or scheme from port, if necessary and
           possible */
        if (mPort == 443 && mScheme.equals("")) {
            mScheme = "https";
        } else if (mPort == -1) {
            if (mScheme.equals("https"))
                mPort = 443;
            else
                mPort = 80; // default
        }
        if (mScheme.equals("")) mScheme = "http";
    }

    @Override
    public String toString() {
        String port = "";
        if ((mPort != 443 && mScheme.equals("https")) ||
            (mPort != 80 && mScheme.equals("http"))) {
            port = ":" + Integer.toString(mPort);
        }
        String authInfo = "";
        if (mAuthInfo.length() > 0) {
            authInfo = mAuthInfo + "@";
        }

        return mScheme + "://" + authInfo + mHost + port + mPath;
    }

    public void setScheme(String scheme) {
      mScheme = scheme;
    }

    public String getScheme() {
      return mScheme;
    }

    public void setHost(String host) {
      mHost = host;
    }

    public String getHost() {
      return mHost;
    }

    public void setPort(int port) {
      mPort = port;
    }

    public int getPort() {
      return mPort;
    }

    public void setPath(String path) {
      mPath = path;
    }

    public String getPath() {
      return mPath;
    }

    public void setAuthInfo(String authInfo) {
      mAuthInfo = authInfo;
    }

    public String getAuthInfo() {
      return mAuthInfo;
    }
}

通過以上方法,可以判斷出一個url是否為真正的url