[英]Convert partial url string to full url string
我正在开发一个网络浏览器。 是否有一种内置方法可以将部分 url 字符串(如"example.com"
或"www.example.com"
等)转换为"http://www.example.com/"
?
我不确定这是否会解决您的问题 - 但我可能建议使用 URL 类中的构建来尝试解决此问题。 请查看以下链接并确定它们是否有帮助。
假设您正在尝试对输入到 Web 浏览器位置栏中的String
进行操作,那么您唯一可以放心做的事情就是检查该字符串是否已经以“http://”或“https://”开头或一些其他方案(例如“ftp://”),如果没有,则在开头添加“http://”。
正如评论中提到的,假设子域应设置为“www”是错误的,因为并非所有 Web 服务器都配置了此子域。 (如果网站所有者愿意,可以轻松地将 Web 服务器配置为将请求重定向到“www”子域。)
所以我想说你需要的代码很简单:
// Create a static final class field.
static final Pattern STARTS_WITH_SCHEME = Pattern.compile("^ *[a-z]+://");
// Then within your method code make use of the Pattern.
if (!STARTS_WITH_SCHEME.matcher(urlString).find()) {
urlString = "http://" + urlString.trim();
}
这将检查您的urlString
是否以任何方案开头,后跟冒号和双斜杠。 如果没有,那么“http://”将被添加到您的urlString
。 请注意, Pattern
允许在urlString
的最开始出现空格,然后方法代码将它们修剪掉。
从我从你的问题中了解到的,这就是你假装的。
String url = "www.example.com"
//Checks if the string does not start with http://
if (!url.startsWith("http://" && !url.endsWith("/") {
//Appends the http in the begginning of the String
url.insert(0, "http://");
}
//Checks if the string does not end with /
if (!url.endsWith("/") {
//Appends the slash in the end of the url
url.append("/");
}
请注意,我添加了 url String 的验证,因为在某些情况下,我猜您不确定 url 格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.