我想验证网址字符串,并在需要时添加http://www。 该网址可能是" google.com"或" google.co.in"所以很难在字符串的末尾进行中继。
我该怎么做?
答案 0 :(得分:1)
if (!url.contains("http://www") {
url = "http://www" + url;
}
答案 1 :(得分:1)
您可以尝试正则表达式:
public static final String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";
Pattern p = Pattern.compile(URL_REGEX);
Matcher m = p.matcher("example.com");//replace with string to compare
if(m.find()) {
System.out.println("String contains URL");
}
答案 2 :(得分:1)
嗯,在我看来,验证网址的最佳方法是实际尝试。有很多方法搞砸了网址,然后是http://或http s ://的东西。
无论如何,如果您想要实际测试URL以确保它真正有效并且实际上是在线,那么这里是另一种选择。是的,我知道它要慢得多,但至少你肯定知道这很好。
以下是基本代码:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
public class ValidateURL {
public static void main(String[] args) {
String urlString = "https://www.google.com";
// Make sure "http://" or "https://" is located
// at the beginning of the supplied URL.
if (urlString.matches("((http)[s]?(://).*)")) {
try {
final URL url = new URL(urlString);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
int responseCode = huc.getResponseCode();
if (responseCode != 200) {
System.out.println("There was a problem connecting to:\n\n" +
urlString + "\n\nResponse Code: [" + responseCode + "]");
}
System.out.println("The supplied URL is GOOD!");
}
catch (UnknownHostException | MalformedURLException ex) {
System.out.println("Either the supplied URL is good or\n" +
"there is No Network Connection!\n" + urlString);
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
答案 3 :(得分:0)
如果您只想验证String是否为有效URL,则可以使用Apache Validator类。示例代码也在那里。