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 ?
You'll need to URL encode the address.
See :-
http://download.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html
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
精彩评论