简体   繁体   中英

How do I retain the encoding in argument when using MessageFormat in Java

I am trying to use MessageFormat as follows,

String downloadsUrl = "http://host/downloads?tags={0}";
Object[] formatArgs = {"sequence%20diagram"};
String url = new MessageFormat(downloadsUrl).format(formatArgs);

However, when I look at the final url string, it is, http://host/downloads?tags=sequence diagram

Is there someway to retain the %20 and not have MessageFormat replace it with a space?

The code you provided does not add the space the code above returns "http://host/downloads?tags=sequence%20diagram"

Your target servlet is doing the substitution. Whatever "/downloads" is mapped to is parsing the tags parameter and performing url decoding. You can reconstruct possible encodings as follows. You will need to handle the UnsupportedEncodingException in the following.

String encoded = URLEncoder.encode( request.getParameter( name ), "UTF8" );

Unfortunately this is only a possible encoding and by default will convert spaces to "+". To get the "%20" back you will need to resort to

encoding = encoding.replaceAll( "+", "%20" );

This may work for you or not. In general it is more advisable to normalize on the decoded value instead of the encoded value as there are many possible encodings per decoded value.

基于此,我将猜测在值周围加上单引号是可行的...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM