com.github.azbh111.utils.java.url.UrlUtils Maven / Gradle / Ivy
Show all versions of utils-java Show documentation
package com.github.azbh111.utils.java.url;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
/**
* @author pyz
* @date 2018/9/13 下午8:47
*/
public class UrlUtils {
/**
* 移除链接中的域名部分
* http://host/x/x/... -> x/x/...
*
* @param url
* @return
*/
public static String removeHost(String url) {
if (url == null || url.isEmpty()) {
return url;
}
if (!url.startsWith("http")) {
if (url.indexOf("/") == 0) {
return url.substring(1);
}
return url;
}
url = url.replace("http://", "").replace("https://", "");
int idx = url.indexOf("/");
if (idx == -1) {
return "";
}
return url.substring(idx + 1);
}
/**
* 从url中获取host
*
* @param url
* @return
*/
public static String getHost(String url) {
if (url == null) {
return null;
}
if (url.startsWith("http://")) {
url = url.substring("http://".length());
} else if (url.startsWith("https://")) {
url = url.substring("https://".length());
} else {
return null;
}
if (url.isEmpty()) {
return null;
}
int dot = url.indexOf('/');
if (dot == -1) {
return url;
}
if (dot == 0) {
return null;
}
return url.substring(0, dot);
}
/**
* 从url上读取文件的后缀名
*
* null -> null
* 非法url ->
* http://host/x/x/.../abc.jpg -> jpg
* http://host/x/x/.../abc. ->
* http://host/abc.jpg -> jpg
* http://host/abc. ->
* http://host/x/x/.../abc ->
* http://host ->
*
* @param url
* @return
*/
public static String getFileSuffix(String url) {
if (url == null) {
return null;
}
int dot = url.indexOf("//");
if (dot == -1) {
return "";
}
int dot2 = url.lastIndexOf('/');
if (dot2 == dot + 1) {
return ""; // 非法的url
}
int dot3 = url.lastIndexOf('.');
if (dot3 < dot2) {
return "";
}
return url.substring(dot3 + 1);
}
public static String urlEncode(String url) {
return urlEncode(url, Charset.defaultCharset());
}
public static String urlEncode(String url, Charset encoding) {
try {
return URLEncoder.encode(url, encoding.name());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
public static String urlDecode(String url) {
return urlDecode(url, Charset.defaultCharset());
}
public static String urlDecode(String url, Charset encoding) {
try {
return URLDecoder.decode(url, encoding.name());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
}