HTTP URL Address Encoding in Java

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

    Yeah URL encoding is going to encode that string so that it would be passed properly in a url to a final destination. For example you could not have http://stackoverflow.com?url=http://yyy.com. UrlEncoding the parameter would fix that parameter value.

    So i have two choices for you:

    1. Do you have access to the path separate from the domain? If so you may be able to simply UrlEncode the path. However, if this is not the case then option 2 may be for you.

    2. Get commons-httpclient-3.1. This has a class URIUtil:

      System.out.println(URIUtil.encodePath("http://example.com/x y", "ISO-8859-1"));

    This will output exactly what you are looking for, as it will only encode the path part of the URI.

    FYI, you'll need commons-codec and commons-logging for this method to work at runtime.

提交回复
热议问题