java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

前端 未结 6 1862
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 21:08

I get the following warning when using java.net.URLEncoder.encode:

warning: [deprecation] encode(java.lang.String)
         in java.net.URLEncoder has         


        
6条回答
  •  醉话见心
    2020-11-29 21:53

    The usage of org.apache.commons.httpclient.URI is not strictly an issue; what is an issue is that you target the wrong constructor, which is depreciated.

    Using just

    new URI( [string] );
    

    Will indeed flag it as depreciated. What is needed is to provide at minimum one additional argument (the first, below), and ideally two:

    1. escaped: true if URI character sequence is in escaped form. false otherwise.
    2. charset: the charset string to do escape encoding, if required

    This will target a non-depreciated constructor within that class. So an ideal usage would be as such:

    new URI( [string], true, StandardCharsets.UTF_8.toString() );
    

    A bit crazy-late in the game (a hair over 11 years later - egad!), but I hope this helps someone else, especially if the method at the far end is still expecting a URI, such as org.apache.commons.httpclient.setURI().

提交回复
热议问题