HTTP URL Address Encoding in Java

前端 未结 26 1403
醉酒成梦
醉酒成梦 2020-11-22 01:35

My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encod

26条回答
  •  别那么骄傲
    2020-11-22 02:07

    You can use a function like this. Complete and modify it to your need :

    /**
         * Encode URL (except :, /, ?, &, =, ... characters)
         * @param url to encode
         * @param encodingCharset url encoding charset
         * @return encoded URL
         * @throws UnsupportedEncodingException
         */
        public static String encodeUrl (String url, String encodingCharset) throws UnsupportedEncodingException{
                return new URLCodec().encode(url, encodingCharset).replace("%3A", ":").replace("%2F", "/").replace("%3F", "?").replace("%3D", "=").replace("%26", "&");
        }
    

    Example of use :

    String urlToEncode = ""http://www.growup.com/folder/intérieur-à_vendre?o=4";
    Utils.encodeUrl (urlToEncode , "UTF-8")
    

    The result is : http://www.growup.com/folder/int%C3%A9rieur-%C3%A0_vendre?o=4

提交回复
热议问题