HTTP URL Address Encoding in Java

前端 未结 26 1365
醉酒成梦
醉酒成梦 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:12

    I read the previous answers to write my own method because I could not have something properly working using the solution of the previous answers, it looks good for me but if you can find URL that does not work with this, please let me know.

    public static URL convertToURLEscapingIllegalCharacters(String toEscape) throws MalformedURLException, URISyntaxException {
                URL url = new URL(toEscape);
                URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
                //if a % is included in the toEscape string, it will be re-encoded to %25 and we don't want re-encoding, just encoding
                return new URL(uri.toString().replace("%25", "%"));
    }
    

提交回复
热议问题