Skip to content

Instantly share code, notes, and snippets.

@liangzai-cool
Last active February 26, 2019 18:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liangzai-cool/440ad8eee618d0ba0eb7aabc4d02c2aa to your computer and use it in GitHub Desktop.
Save liangzai-cool/440ad8eee618d0ba0eb7aabc4d02c2aa to your computer and use it in GitHub Desktop.
convert relative url to absolute url and beautify the result in java.
```
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtils {
public static void main(String[] args) throws MalformedURLException {
String urlString = "https://www.google.com///images//branding/1234567890/..\\googlelogo/abcdefg/../1x/googlelogo_color_272x92dp.png";
System.out.println(absUrl(urlString));
System.out.println(absUrl(urlString, "/abc/../def.png"));
}
public static String absUrl(String baseUrlString, String urlString) throws MalformedURLException, URISyntaxException {
if (urlString == null || urlString.trim().length() == 0) urlString = "";
URL baseUrl = new URL(baseUrlString);
URL url = new URL(baseUrl, urlString);
urlString = url.toString().replaceAll("\\\\+", "/");
url = new URL(urlString);
String uri = url.getPath();
String uriString = uri.replaceAll("/+", "/");
urlString = url.toString().replaceAll(uri, uriString);
int index = urlString.indexOf("/..");
if (index < 0) return urlString;
String urlStringLeft = urlString.substring(0, index) + "/";
String urlStringRight = urlString.substring(index + 1);
return absUrl(urlStringLeft, urlStringRight);
}
public static String absUrl(String url) {
try {
return absUrl(url, null);
} catch (MalformedURLException | URISyntaxException e) {
log.error("convert url to absUrl error", e);
return url;
}
}
}
```
convert `https://www.google.com///images//branding/1234567890/..\\googlelogo/abcdefg/../1x/googlelogo_color_272x92dp.png`
to `https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png`
or
convert `https://www.google.com///images//branding/1234567890/..\\googlelogo/abcdefg/../1x/googlelogo_color_272x92dp.png` & `/abc/../def.png`
to `https://www.google.com/def.png`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment