Java 如何将 url 中的特殊字符作为参数值处理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19515616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:56:28  来源:igfitidea点击:

How to handle special characters in url as parameter values?

javajavascripthtmlhttpspring-mvc

提问by Puneet Purohit

Can anyone suggest how to handle below url as values of parameter of strLocation is haveing special charecters ? Thanks in advance

任何人都可以建议如何处理以下 url,因为 strLocation 的参数值具有特殊字符?提前致谢

http://localhost:8080/safp/contacts/FirmAddress.do?btnAction=FirmAddress&firmId=122379069&strLocation=!@#$%^&*()_+&async=true&newAccID=112

采纳答案by Juned Ahsan

Use URLEncoderto encode your URL string with special characters.When encoding a String, the following rules apply:

使用URLEncoder使用特殊字符对 URL 字符串进行编码。对字符串进行编码时,以下规则适用:

  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same.
  • The special characters ".", "-", "*", and "_" remain the same.
  • The space character " " is converted into a plus sign "+".
  • All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented
    by the 3-character string "%xy", where xy is the two-digit
    hexadecimal representation of the byte. The recommended encoding
    scheme to use is UTF-8. However, for compatibility reasons, if an
    encoding is not specified, then the default encoding of the platform
    is used.
  • 字母数字字符“a”到“z”、“A”到“Z”和“0”到“9”保持不变。
  • 特殊字符“.”、“-”、“*”和“_”保持不变。
  • 空格字符“”被转换为加号“+”。
  • 所有其他字符都是不安全的,首先使用某种编码方案将其转换为一个或多个字节。然后每个字节
    由 3 个字符的字符串“%xy”表示,其中 xy 是
    字节的两位十六进制表示。推荐使用的编码
    方案是 UTF-8。但是,出于兼容性原因,如果
    未指定编码,
    则使用平台的默认编码。

For example using UTF-8 as the encoding scheme the string The string ü@foo-barwould get converted to The+string+%C3%BC%40foo-barbecause in UTF-8 the character ü is encoded as two bytes C3 (hex) and BC (hex), and the character @ is encoded as one byte 40 (hex).

例如,使用 UTF-8 作为字符串The string ü@foo-bar将被转换为的编码方案,The+string+%C3%BC%40foo-bar因为在 UTF-8 中,字符 ü 被编码为两个字节 C3(十六进制)和 BC(十六进制),而字符 @ 被编码为一个字节 40(十六进制)。

回答by Tarsem Singh

Use URLEncoder.encode()

使用URLEncoder.encode()

String url="http://localhost:8080/safp/contacts/FirmAddress.do?btnAction=FirmAddress&firmId="+URLEncoder.encode("122379069","UTF-8")+"&strLocation="+URLEncoder.encode("!@#$%^&*()_+","UTF-8")+"&async=true&newAccID=112";

Note: Don't encodethe whole url because it will also encode the //from http://

注意:不要encode使用整个 url,因为它也会对//from进行编码http://