0

请让我知道encodeURI()Java 中的 JavaScript 等价物。

虽然我知道这相当于encodeURIComponent().

result = URLEncoder.encode(component, "UTF-8")
    .replaceAll("\\%28", "(") 
    .replaceAll("\\%29", ")") 
    .replaceAll("\\+", "%20") 
    .replaceAll("\\%27", "'") 
    .replaceAll("\\%21", "!") 
    .replaceAll("\\%7E", "~");" 
4

1 回答 1

0

你可以尝试这样的事情;

    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", "&");
    }

需要做更多的工作来确保它支持嵌套和完整的规范。

于 2014-11-20T18:38:34.320 回答