encodeURI等效不需要URLEncoder.encode,相当于encodeURIComponent()

时间:2012-04-18 09:50:04

标签: java urlencode

请告诉我Java中等效的JavaScript中的encodeURI()

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

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

1 个答案:

答案 0 :(得分: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", "&");
    }

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