英文:
Remove port number from a url in java
问题
我想在Java中编写一个函数,如果端口是默认端口,则移除该端口。
因此,如果给定:
String url80 = "http://www.somewhere.com:80/someplace";
它将返回:
String urlNo80 = "http://www.somewhere.com/someplace";
如果给定:
String url443 = "https://www.somewhere.com:443/someplace";
它将返回:
String urlNo443 = "https://www.somewhere.com/someplace";
有比以下方式更好的方法吗?
public String removePortIfDefault(String inUrl) {
String returnUrl = inUrl;
if (inUrl.contains("http://") && inUrl.contains(":80")) {
returnUrl = inUrl.replaceAll(":80", "");
}
if (inUrl.contains("https://") && inUrl.contains(":443")) {
returnUrl = inUrl.replaceAll(":443", "");
}
return returnUrl;
}
英文:
I want to write a function in java which removes the port if it is the default port.
So if given
String url80 = "http://www.somewhere.com:80/someplace";
it will return
String urlNo80 = "http://www.somewhere.com/someplace";
And if given
String url443 = "https://www.somewhere.com:443/someplace";
It will return
String urlNo443 = "https://www.somewhere.com/someplace";
Is there a better way to do it than
public String removePortIfDefault(String inUrl) {
String returnUrl = inUrl;
if (inUrl.contains("http://") && inUrl.contains(":80")) {
returnUrl = inUrl.replaceAll(":80", "");
}
if (inUrl.contains("https://") && inUrl.contains(":443")) {
returnUrl = inUrl.replaceAll(":443", "");
}
return returnUrl;
}
答案1
得分: 4
你可以使用replaceFirst(或replaceAll)与正则表达式:
String urlNo80 = url80.replaceFirst(":\\d+", "");
英文:
You can use replaceFirst (or replaceAll) with a regular expression
String urlNo80 = url80.replaceFirst(":\\d+", "");
答案2
得分: 4
不要使用字符串操作处理URL。Java中有相应的类可供使用。
String url80 = "http://www.somewhere.com:80/someplace";
// 使用 java.net.URI
URI uri = URI.create(url80);
uri = new URI(uri.getScheme(), uri.getHost(), uri.getPath(), uri.getFragment());
String urlNo80 = uri.toString(); // http://www.somewhere.com/someplace
// 使用 java.net.URL
URL url = new URL(url80);
url = new URL(url.getProtocol(), url.getHost(), url.getFile());
String urlNo80 = url.toString(); // http://www.somewhere.com/someplace
英文:
Don't use string manipulation to work with a URL. Java has classes for that.
String url80 = "http://www.somewhere.com:80/someplace";
// Using java.net.URI
URI uri = URI.create(url80);
uri = new URI(uri.getScheme(), uri.getHost(), uri.getPath(), uri.getFragment());
String urlNo80 = uri.toString(); // http://www.somewhere.com/someplace
// Using java.net.URL
URL url = new URL(url80);
url = new URL(url.getProtocol(), url.getHost(), url.getFile());
String urlNo80 = url.toString(); // http://www.somewhere.com/someplace
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论