URL manipulation
I want to do a little manipulation with URLs.
It is required to add a sub domain in already created URL like shown below
Inputs
String inputURL = "http://www.myhost.com";
String subdomain = "newlocation";
output
String output = "http://www.newlocation.myhost.com";
I was thinking if there is any existing utility class that can do this for me. expert can have someth开发者_如何学Pythoning to say.
Thanks for your help !
Note that "www" is also subdomain. So you are actually appending another subdomain.
String inputURL = "http://www.myhost.com";
String subdomain = "newlocation";
URL url = new URL(inputURL);
String[] domainParts = url.getHost().split("\\.");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < domainParts.length; i ++) {
if (i == 1) {
sb.append(subdomain + ".");
}
sb.append(domainParts[i] + ".");
}
String query = "";
String port = "";
if (url.getQuery() != null) {
query = "?" + url.getQuery();
}
if (url.getPort() != -1) {
port = url.getPort() + "";
}
String output = url.getProtocol() + ":" + port + "//" + sb.toString() + "/" + url.getPath() + query;
System.out.println(output);
It is sufficient to parse only the host part of the URL and use the URI to render.
URL url = new URL(inputURL);
String host = url.getHost().replaceAll("(([.][^.]+){2,2})$", "." + subdomain + "$1");
String newUrl = new URI(url.getProtocol(), host, url.getPath(), url.getQuery(), null).toString();
Perhaps:
String output = inputURL.replaceAll("(http://[^.]+\\.)(.*)", "$1" + subdomain + ".$2");
Look at StringBuffer (Link to the Java API doc) and then you will probably need to use one of the insert()
methods
精彩评论