android java 如何判断一个url地址为有效url

128 篇文章 0 订阅

我们在android 和java开发中可能会遇到一个问题,就是判断用户输入的url或者从网页或其他地方复制来的url是否为一个有效的url,下面是一些方法,供大家参考:

在没有encode的情况下可以使用下面方法

[java]  view plain  copy
  1. URI uriObj = new URI(url);  

这个方法来进行判定,如果该方法抛出异常URISyntaxException,那么就说明这个url不是一个正确的url,不过当遇到一个url地址中包含字符串^的时候,也会抛出异常,可以这个含有^的链接却是一个有效的地址,比如百度中的某些地址,因此可以通过下面的代码进行改进:

[java]  view plain  copy
  1. URL urlObj = new URL(url);  
  2. URI uriObj = new URI(urlObj.getProtocol(), urlObj.getHost(), urlObj.getPath(), urlObj.getQuery(), null);  
这两个方法分别会抛出MalformedURLException和URISyntaxException.

不过如果你想对一些schemes进行限制,可以加入以下代码:

[java]  view plain  copy
  1. private static final String acceptableSchemes[] = {  
  2.         "http:",  
  3.         "https:",  
  4.         "file:"  
  5. };  
  6.   
  7. private static boolean urlHasAcceptableScheme(String url) {  
  8.     if (url == null) {  
  9.         return false;  
  10.     }  
  11.   
  12.     for (int i = 0; i < acceptableSchemes.length; i++) {  
  13.         if (url.startsWith(acceptableSchemes[i])) {  
  14.             return true;  
  15.         }  
  16.     }  
  17.     return false;  
  18. }  
  19.   
  20. private String isValidUrl(String incommingString) throws Exception{  
  21.     String url = "";  
  22.     URL urlObj = new URL(incommingString);  
  23.     URI uriObj = new URI(urlObj.getProtocol(), urlObj.getHost(), urlObj.getPath(), urlObj.getQuery(), null);  
  24.     String scheme = uriObj.getScheme();  
  25.     if (!urlHasAcceptableScheme(incommingString)) {  
  26.         if (scheme != null) {  
  27.             throw new URISyntaxException("""");  
  28.         }  
  29.     }  
  30.     //此处需要对url进行赋值操作,例如需要加http://等  
  31. p;       return url;  
  32. }  

对于android开发,还可以以这样处理:

[java]  view plain  copy
  1. import android.util.Patterns;//android包下的  
  2.   
  3. if (Patterns.WEB_URL.matcher(searchContent).matches()) {  
  4.      //符合标准  
  5. else{  
  6.      //不符合标准  
  7. }  

接下来提供一个完整的封装类,不但提供了对url的校验,还对url的大部分信息进行了封装操作,代码如下:

[java]  view plain  copy
  1. package 随便写;  
  2.   
  3. import static android.util.Patterns.GOOD_IRI_CHAR;  
  4.   
  5. import java.util.Locale;  
  6. import java.util.regex.Matcher;  
  7. import java.util.regex.Pattern;  
  8.   
  9. public class WebAddress {  
  10.   
  11.     private String mScheme;  
  12.     private String mHost;  
  13.     private int mPort;  
  14.     private String mPath;  
  15.     private String mAuthInfo;  
  16.   
  17.     static final int MATCH_GROUP_SCHEME = 1;  
  18.     static final int MATCH_GROUP_AUTHORITY = 2;  
  19.     static final int MATCH_GROUP_HOST = 3;  
  20.     static final int MATCH_GROUP_PORT = 4;  
  21.     static final int MATCH_GROUP_PATH = 5;  
  22.   
  23.     /* ENRICO: imported the ParseExeption here */  
  24.     public static class ParseException extends RuntimeException {  
  25.         public String response;  
  26.   
  27.         ParseException(String response) {  
  28.             this.response = response;  
  29.         }  
  30.     }  
  31. //根据正则表达式进行判断  
  32.     static Pattern sAddressPattern = Pattern.compile(  
  33.             /* scheme    */ "(?:(http|https|file)\\:\\/\\/)?" +  
  34.             /* authority */ "(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?" +  
  35.             /* host      */ "([" + GOOD_IRI_CHAR + "%_-][" + GOOD_IRI_CHAR + "%_\\.-]*|\\[[0-9a-fA-F:\\.]+\\])?" +  
  36.             /* port      */ "(?:\\:([0-9]*))?" +  
  37.             /* path      */ "(\\/?[^#]*)?" +  
  38.             /* anchor    */ ".*", Pattern.CASE_INSENSITIVE);  
  39.   
  40.     /** parses given uriString. */  
  41. //用法:将需要判断的url传入,new WebAddress(address) 如果抛出异常,则会出现问题  
  42.  public WebAddress(String address) throws ParseException {  
  43.         if (address == null) {  
  44.             throw new NullPointerException();  
  45.         }  
  46.   
  47.         // android.util.Log.d(LOGTAG, "WebAddress: " + address);  
  48.   
  49.         mScheme = "";  
  50.         mHost = "";  
  51.         mPort = -1;  
  52.         mPath = "/";  
  53.         mAuthInfo = "";  
  54.   
  55.         Matcher m = sAddressPattern.matcher(address);  
  56.         String t;  
  57.         if (m.matches()) {  
  58.             t = m.group(MATCH_GROUP_SCHEME);  
  59.             if (t != null) mScheme = t.toLowerCase(Locale.getDefault());  
  60.             t = m.group(MATCH_GROUP_AUTHORITY);  
  61.             if (t != null) mAuthInfo = t;  
  62.             t = m.group(MATCH_GROUP_HOST);  
  63.             if (t != null) mHost = t;  
  64.             t = m.group(MATCH_GROUP_PORT);  
  65.             if (t != null && t.length() > 0) {  
  66.                 // The ':' character is not returned by the regex.  
  67.                 try {  
  68.                     mPort = Integer.parseInt(t);  
  69.                 } catch (NumberFormatException ex) {  
  70.                     throw new ParseException("Bad port");  
  71.                 }  
  72.             }  
  73.             t = m.group(MATCH_GROUP_PATH);  
  74.             if (t != null && t.length() > 0) {  
  75.                 /* handle busted myspace frontpage redirect with 
  76.                    missing initial "/" */  
  77.                 if (t.charAt(0) == '/') {  
  78.                     mPath = t;  
  79.                 } else {  
  80.                     mPath = "/" + t;  
  81.                 }  
  82.             }  
  83.   
  84.         } else {  
  85.             // nothing found... outa here  
  86.             throw new ParseException("Bad address");  
  87.         }  
  88.   
  89.         /* Get port from scheme or scheme from port, if necessary and 
  90.            possible */  
  91.         if (mPort == 443 && mScheme.equals("")) {  
  92.             mScheme = "https";  
  93.         } else if (mPort == -1) {  
  94.             if (mScheme.equals("https"))  
  95.                 mPort = 443;  
  96.             else  
  97.                 mPort = 80// default  
  98.         }  
  99.         if (mScheme.equals("")) mScheme = "http";  
  100.     }  
  101.   
  102.     @Override  
  103.     public String toString() {  
  104.         String port = "";  
  105.         if ((mPort != 443 && mScheme.equals("https")) ||  
  106.             (mPort != 80 && mScheme.equals("http"))) {  
  107.             port = ":" + Integer.toString(mPort);  
  108.         }  
  109.         String authInfo = "";  
  110.         if (mAuthInfo.length() > 0) {  
  111.             authInfo = mAuthInfo + "@";  
  112.         }  
  113.   
  114.         return mScheme + "://" + authInfo + mHost + port + mPath;  
  115.     }  
  116.   
  117.     public void setScheme(String scheme) {  
  118.       mScheme = scheme;  
  119.     }  
  120.   
  121.     public String getScheme() {  
  122.       return mScheme;  
  123.     }  
  124.   
  125.     public void setHost(String host) {  
  126.       mHost = host;  
  127.     }  
  128.   
  129.     public String getHost() {  
  130.       return mHost;  
  131.     }  
  132.   
  133.     public void setPort(int port) {  
  134.       mPort = port;  
  135.     }  
  136.   
  137.     public int getPort() {  
  138.       return mPort;  
  139.     }  
  140.   
  141.     public void setPath(String path) {  
  142.       mPath = path;  
  143.     }  
  144.   
  145.     public String getPath() {  
  146.       return mPath;  
  147.     }  
  148.   
  149.     public void setAuthInfo(String authInfo) {  
  150.       mAuthInfo = authInfo;  
  151.     }  
  152.   
  153.     public String getAuthInfo() {  
  154.       return mAuthInfo;  
  155.     }  
  156. }  
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值