简体   繁体   English

在Java中使用MessageFormat时如何保留参数中的编码

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

I am trying to use MessageFormat as follows, 我正在尝试按以下方式使用MessageFormat

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 但是,当我查看最终的URL字符串时,它是http:// host / downloads?tags = sequence

Is there someway to retain the %20 and not have MessageFormat replace it with a space? 是否可以保留%20并且没有MessageFormat用空格替换?

The code you provided does not add the space the code above returns "http://host/downloads?tags=sequence%20diagram" 您提供的代码未添加上面代码返回的空间“ http:// host / downloads?tags = sequence%20diagram”

Your target servlet is doing the substitution. 您的目标servlet正在进行替换。 Whatever "/downloads" is mapped to is parsing the tags parameter and performing url decoding. 映射到“ / downloads”的任何内容都是解析标签参数并执行url解码。 You can reconstruct possible encodings as follows. 您可以按以下方式重构可能的编码。 You will need to handle the UnsupportedEncodingException in the following. 您将需要在下面处理UnsupportedEncodingException。

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 要取回“%20”,您需要诉诸

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. 通常,更可取的是对解码值而不是编码值进行归一化,因为每个解码值有许多可能的编码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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