Last active
February 26, 2019 18:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
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