简体   繁体   English

如何为特殊字符表示字符串 URL?

[英]How to represent a string URL for special character?

I am newbie to this and couldn't find exact answer.我是新手,找不到确切的答案。 I have special characters in a URL such as,我在 URL 中有特殊字符,例如,

"&", "#", "?" "<"

it causes a problems.它会导致问题。 (If someone can suggest how to deal with such situation then it would be an additional help). (如果有人可以建议如何处理这种情况,那将是一个额外的帮助)。 My main problem is that, how can I represent a string literal in JAVA for following kind of URL?我的主要问题是,如何在 JAVA 中为以下 URL 表示字符串文字?

"x###y"

I learned that we need to put its hex code value (using % ).我了解到我们需要输入它的hex代码值(使用% )。 Can someone suggest that exact answer to fix this URL problem?有人可以提出解决此 URL 问题的确切答案吗?

java.net.URLEncoder.encode(YOUR_STRING, "UTF-8");

See also this question for a way to only encode the part of the url you need:另请参阅此问题,了解仅对您需要的 url 部分进行编码的方法:

The answer depends on where the data is in the URL.答案取决于数据在 URL 中的位置。 There will be different encoding rules for different parts of the URL. URL的不同部分会有不同的编码规则。

The exact form may also depend on what URI format the server is expecting.确切的形式也可能取决于服务器期望的 URI 格式。

Parameters in the query part can usually be encoded as application/x-www-form-urlencoded using the URLEncoder :查询部分中的参数通常可以使用URLEncoder编码为application/x-www-form-urlencoded

String query = URLEncoder.encode("key1", "UTF-8")
             + "="
             + URLEncoder.encode("value1", "UTF-8")
             + "&"
             + URLEncoder.encode("key2", "UTF-8")
             + "="
             + URLEncoder.encode("value2", "UTF-8");

If you need to encode in other parts of the URI (the path part, or the fragment part) read this .如果您需要在 URI 的其他部分(路径部分或片段部分)进行编码,请阅读.

URLEncoder is not for encoding URLs it is there to encode form data

see the following link for more details有关详细信息,请参阅以下链接

HTTP URL Address Encoding in Java HTTP URL Java中的地址编码

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

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