简体   繁体   中英

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,

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

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?

"x###y"

I learned that we need to put its hex code value (using % ). Can someone suggest that exact answer to fix this URL problem?

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:

The answer depends on where the data is in the URL. There will be different encoding rules for different parts of the URL.

The exact form may also depend on what URI format the server is expecting.

Parameters in the query part can usually be encoded as application/x-www-form-urlencoded using the URLEncoder :

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 .

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

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