你可以尝试这样的事情;
public static String encodeURIComponent(String url) {
try {
return URLEncoder.encode(url, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
//the slow option:
//new ScriptEngineManager().getEngineByName("JavaScript")...etc
} catch (UnsupportedEncodingException e) {
//never
}
}
public static String encodeURI(String url) {
return encodeURIComponent(url)
.replaceAll("%3A", ":")
.replaceAll("%2F", "/")
.replaceAll("%3F", "?")
.replaceAll("%3D", "=")
.replaceAll("%26", "&");
}
需要做更多的工作来确保它支持嵌套和完整的规范。