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

StackOverflow https://stackoverflow.com/questions/8345796

  •  27-10-2019
  •  | 
  •  

سؤال

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.

نصائح أخرى

Based on this I'm going to guess putting single quotes around the value would work...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top