web-dev-qa-db-ja.com

URLからドメイン/ホスト名を取得する最も速い方法は何ですか?

文字列のURLの大きなリストを調べ、それらからドメイン名を抽出する必要があります。

例えば:

http://www.stackoverflow.com/questions抽出www.stackoverflow.com

私は元々new URL(theUrlString).getHost()を使用していましたが、URLオブジェクトの初期化はプロセスに多くの時間を追加し、不要に思われます。

同じくらい信頼できるホスト名を抽出するより速い方法はありますか?

ありがとう

編集:私の間違い、はいwww。上記のドメイン名の例に含まれます。また、これらのURLはhttpまたはhttpsの場合があります

17
cottonBallPaws

httpsなどを処理したい場合は、次のようにすることをお勧めします。

_int slashslash = url.indexOf("//") + 2;
domain = url.substring(slashslash, url.indexOf('/', slashslash));
_

これには、実際にはドメイン名の一部であるwww部分が(URL.getHost()と同じように)含まれていることに注意してください。

コメントを介してリクエストされた編集

役立つと思われる2つの方法を次に示します。

_/**
 * 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;
    }
}
_
37
aioobe

URLを選択しない「高速」な方法を実装する場合は、かなり注意が必要です。 URLには多くの潜在的なばらつきがあり、「高速」メソッドが失敗する原因になる可能性があります。例えば:

  • スキーム(プロトコル)の部分は、大文字と小文字の任意の組み合わせで記述できます。例えば「http」、「Http」、「HTTP」は同等です。

  • 権限部分には、「 http://[email protected]:8080/index.html 」のように、オプションでユーザー名やポート番号を含めることができます。

  • DNSは大文字と小文字を区別しないため、URLのホスト名部分も(事実上)大文字と小文字を区別しません。

  • URLのスキームまたは権限コンポーネントで予約されていない文字を%エンコードすることは合法です(非常に不規則です)。スキームを照合(または削除)するとき、またはホスト名を解釈するときは、これを考慮する必要があります。 %エンコードされた文字を含むホスト名は、%エンコードされたシーケンスがデコードされたホスト名と同等と定義されます。

ここで、削除するURLを生成するプロセスを完全に制御できる場合は、これらの機能を無視できます。しかし、それらがドキュメントまたはWebページから収集された場合、または人間によって入力された場合、コードが「異常な」URLに遭遇した場合に何が起こるかを検討することをお勧めします。


URLオブジェクトの構築にかかる時間が懸念される場合は、代わりにURIオブジェクトの使用を検討してください。特に、URIオブジェクトはホスト名部分のDNSルックアップを試みません。

9
Stephen C

私は、URLのドメイン名を抽出し、単純な文字列マッチングを使用するメソッド(以下を参照)を作成しました。実際に行うのは、最初の_"://"_(または_0_が含まれていない場合はインデックス_"://"_)と最初の後続の_"/"_(またはインデックスString.length()後続の_"/"_がない場合)。残りの、先行する"www(_)*."ビットは切り落とされます。これで十分でない場合もあると思いますが、ほとんどの場合それで十分です。

私は here を読んで、_Java.net.URI_クラスがこれを行うことができた(そして_Java.net.URL_クラスよりも好まれた)と述べましたが、URIクラスで問題が発生しました。特に、URI.getHost()は、URLにスキームが含まれていない場合、つまり"http(s)"ビットの場合、null値を返します。

_/**
 * 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;
}
_
2
Adil Hussain

ホストを取得するには別の方法しかありません

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"

1
Ali Azaz Alam

メソッドを試してください:そのクラスの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;
        }

    }
}
1
Mr.Thong

あなたは正規表現を書くことができますか? http://は常に同じであり、最初の「/」が得られるまですべてに一致します。

0
Nanne

それらはすべて整形式の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);
0
Jason LeBrun

正規表現を使用してみてください。

http://download.Oracle.com/javase/6/docs/api/Java/util/regex/Pattern.html

Javaでの正規表現を使用したドメイン名の抽出に関する質問は次のとおりです。

domain.tldを取得するための正規表現

0
Martin