[英]What is the fastest way to get the domain/host name from a URL?
我需要瀏覽大量的字符串url並從中提取域名。
例如:
http://www.stackoverflow.com/questions將摘錄www.stackoverflow.com
我最初使用的是new URL(theUrlString).getHost()
但是URL對象初始化會為進程增加大量時間,而且似乎不需要。
是否有更快的方法來提取可靠的主機名?
謝謝
編輯:我的錯誤,是的www。 將包含在上面的域名示例中。 此外,這些網址可能是http或https
如果你想處理https
等,我建議你這樣做:
int slashslash = url.indexOf("//") + 2;
domain = url.substring(slashslash, url.indexOf('/', slashslash));
請注意,這包括www
部分(就像URL.getHost()
所做的那樣),它實際上是域名的一部分。
通過評論編輯請求
以下兩種方法可能會有所幫助:
/**
* Will take a url such as http://www.stackoverflow.com and return www.stackoverflow.com
*
* @param url
* @return
*/
public static String getHost(String url){
if(url == null || url.length() == 0)
return "";
int doubleslash = url.indexOf("//");
if(doubleslash == -1)
doubleslash = 0;
else
doubleslash += 2;
int end = url.indexOf('/', doubleslash);
end = end >= 0 ? end : url.length();
int port = url.indexOf(':', doubleslash);
end = (port > 0 && port < end) ? port : end;
return url.substring(doubleslash, end);
}
/** Based on : http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.3_r1/android/webkit/CookieManager.java#CookieManager.getBaseDomain%28java.lang.String%29
* Get the base domain for a given host or url. E.g. mail.google.com will return google.com
* @param host
* @return
*/
public static String getBaseDomain(String url) {
String host = getHost(url);
int startIndex = 0;
int nextIndex = host.indexOf('.');
int lastIndex = host.lastIndexOf('.');
while (nextIndex < lastIndex) {
startIndex = nextIndex + 1;
nextIndex = host.indexOf('.', startIndex);
}
if (startIndex > 0) {
return host.substring(startIndex);
} else {
return host;
}
}
您希望在實施“快速”方式取消URL時要非常小心。 URL中存在許多可能導致“快速”方法失敗的可變性。 例如:
方案(協議)部分可以用大寫和小寫字母的任意組合來編寫; 例如“http”,“Http”和“HTTP”是等價的。
權限部分可以可選地包括用戶名和/或端口號,如“ http://you@example.com:8080/index.html ”中所示。
由於DNS不區分大小寫,因此URL的主機名部分也(有效地)不區分大小寫。
% - 對URL中的方案或權限組件中的未保留字符進行編碼是合法的(盡管非常不規則)。 在匹配(或剝離)方案或解釋主機名時,需要考慮這一點。 具有%編碼字符的主機名被定義為等同於解碼了%編碼序列的主機名。
現在,如果您完全控制生成正在剝離的URL的進程,您可能會忽略這些細節。 但如果它們是從文檔或網頁中獲取的,或者是由人類輸入的,那么建議您考慮如果您的代碼遇到“異常”URL會發生什么。
如果您關注的是構建URL對象所需的時間,請考慮使用URI對象。 除了其他好處之外,URI對象不會嘗試對主機名部分進行DNS查找。
我寫了一個方法(見下文),它提取了一個url的域名,並使用簡單的String匹配。 它實際上做的是在第一個"://"
(或索引0
如果沒有包含"://"
)和第一個后續"/"
(或索引String.length()
如果沒有后續"/"
String.length()
之間提取位"/"
)。 剩下的,前面的"www(_)*."
比特被砍掉了。 我敢肯定會出現這種情況不夠好但在大多數情況下應該足夠好的情況!
我在這里讀到java.net.URI
類可以這樣做(並且比java.net.URL
類更java.net.URL
)但我遇到了URI
類的問題。 值得注意的是,如果url不包含該方案,即"http(s)"
位,則URI.getHost()
給出空值。
/**
* Extracts the domain name from {@code url}
* by means of String manipulation
* rather than using the {@link URI} or {@link URL} class.
*
* @param url is non-null.
* @return the domain name within {@code url}.
*/
public String getUrlDomainName(String url) {
String domainName = new String(url);
int index = domainName.indexOf("://");
if (index != -1) {
// keep everything after the "://"
domainName = domainName.substring(index + 3);
}
index = domainName.indexOf('/');
if (index != -1) {
// keep everything before the '/'
domainName = domainName.substring(0, index);
}
// check for and remove a preceding 'www'
// followed by any sequence of characters (non-greedy)
// followed by a '.'
// from the beginning of the string
domainName = domainName.replaceFirst("^www.*?\\.", "");
return domainName;
}
嘗試方法:該類中的getDomainFromUrl()
package com.visc.mobilesecurity.childrencare.utils;
import android.content.Context;
import com.visc.mobilesecurity.antitheft.backwardcompatibility.FroyoSupport;
import com.visc.mobilesecurity.antitheft.util.AntiTheftUtils;
import com.visc.mobilesecurity.constant.Key;
import com.visc.mobilesecurity.util.Prefs;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
/**
* Created by thongnv12 on 3/9/2018.
*/
public class ChildcareUtils {
public static final String[] NATION_DOMAIN = {"af", "ax", "al", "dz", "as", "ad", "ao", "ai", "aq", "ag", "ar", "am", "aw", "ac", "au", "at", "az", "bs", "bh", "bd", "bb", "eus",
"by", "be", "bz", "bj", "bm", "bt", "bo", "bq", "ba", "bw", "bv", "br", "io", "vg", "bn", "bg", "bf", "mm", "bi", "kh", "cm", "ca", "cv", "cat", "ky", "cf", "td", "cl",
"cn", "cx", "cc", "co", "km", "cd", "cg", "ck", "cr", "ci", "hr", "cu", "cw", "cy", "cz", "dk", "dj", "dm", "do", "tl", "ec", "eg", "sv", "gq", "er", "ee", "et", "eu",
"fk", "fo", "fm", "fj", "fi", "fr", "gf", "pf", "tf", "ga", "gal", "gm", "ps", "ge", "de", "gh", "gi", "gr", "gl", "gd", "gp", "gu", "gt", "gg", "gn", "gw", "gy", "ht",
"hm", "hn", "hk", "hu", "is", "in", "id", "ir", "iq", "ie", "im", "il", "it", "jm", "jp", "je", "jo", "kz", "ke", "ki", "kw", "kg", "la", "lv", "lb", "ls", "lr", "ly",
"li", "lt", "lu", "mo", "mk", "mg", "mw", "my", "mv", "ml", "mt", "mh", "mq", "mr", "mu", "yt", "mx", "md", "mc", "mn", "me", "ms", "ma", "mz", "mm", "na", "nr", "np",
"nl", "nc", "nz", "ni", "ne", "ng", "nu", "nf", "kp", "mp", "no", "om", "pk", "pw", "ps", "pa", "pg", "py", "pe", "ph", "pn", "pl", "pt", "pr", "qa", "ro", "ru", "rw",
"re", "bq", "bl", "sh", "kn", "lc", "mf", "fr", "pm", "vc", "ws", "sm", "st", "sa", "sn", "rs", "sc", "sl", "sg", "bq", "sx", "sk", "si", "sb", "so", "so", "za", "gs",
"kr", "ss", "es", "lk", "sd", "sr", "sj", "sz", "se", "ch", "sy", "tw", "tj", "tz", "th", "tg", "tk", "to", "tt", "tn", "tr", "tm", "tc", "tv", "ug", "ua", "ae", "uk",
"us", "vi", "uy", "uz", "vu", "va", "ve", "vn", "wf", "eh", "zm", "zw"};
public static boolean isInNationString(String str) {
for (int index = 0; index < NATION_DOMAIN.length; index++) {
if (NATION_DOMAIN[index].equals(str)) {
return true;
}
}
return false;
}
public static String getDomainFromUrl(String urlStr) {
try {
String result = null;
// URL url = new URL(urlStr);
// result = url.getHost();
// return result;
//
// for test
// check dau cach
if (urlStr.contains(" ")) {
return null;
}
// replace
urlStr = urlStr.replace("https://", "");
urlStr = urlStr.replace("http://", "");
urlStr = urlStr.replace("www.", "");
//
String[] splitStr = urlStr.split("/");
String domainFull = splitStr[0];
String[] splitDot = domainFull.split("\\.");
if (splitDot.length < 2) {
return null;
}
String nationStr = splitDot[splitDot.length - 1];
if (isInNationString(nationStr)) {
if (splitDot.length < 4) {
result = domainFull;
} else {
StringBuilder strResult = new StringBuilder();
int lengthDot = splitDot.length;
strResult.append(splitDot[lengthDot - 3]).append(".");
strResult.append(splitDot[lengthDot - 2]).append(".");
strResult.append(splitDot[lengthDot - 1]);
result = strResult.toString();
}
} else {
if (splitDot.length < 3) {
result = domainFull;
} else {
StringBuilder strResult = new StringBuilder();
int lengthDot = splitDot.length;
strResult.append(splitDot[lengthDot - 2]).append(".");
strResult.append(splitDot[lengthDot - 1]);
result = strResult.toString();
}
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
只有另一種方式來獲得主機
private String getHostName(String hostname) {
// to provide faultproof result, check if not null then return only hostname, without www.
if (hostname != null) {
return hostname.startsWith("www.") ? hostname.substring(4) : getHostNameDFExt(hostname);
}
return hostname;
}
private String getHostNameDFExt(String hostname) {
int substringIndex = 0;
for (char character : hostname.toCharArray()) {
substringIndex++;
if (character == '.') {
break;
}
}
return hostname.substring(substringIndex);
}
現在我們要在從URL中提取后在函數中傳遞主機名
URL url = new URL("https://www.facebook.com/");
String hostname = getHostName(ur.getHost());
Toast.makeText(this, hostname, Toast.LENGTH_SHORT).show();
輸出將是:“ facebook.com ”
你可以寫一個正則表達式嗎? http://始終相同,然后匹配所有內容,直到獲得第一個'/'。
假設它們都是格式正確的URL,但你不知道它們是否是http://,https://等。
int start = theUrlString.indexOf('/');
int start = theUrlString.indexOf('/', start+1);
int end = theUrlString.indexOf('/', start+1);
String domain = theUrlString.subString(start, end);
您可以嘗試使用正則表達式。
http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
這是一個關於使用Java中的正則表達式提取域名的問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.