Java Reference
In-Depth Information
This * string * has * asterisks
This % 25 string % 25 has % 25 percent % 25 signs
This % 2 Bstring % 2 Bhas % 2 Bpluses
This % 2 Fstring % 2 Fhas % 2 Fslashes
This % 22 string % 22 has % 22 quote % 22 marks
This % 3 Astring % 3 Ahas % 3 Acolons
This % 7 Estring % 7 Ehas % 7 Etildes
This % 28 string % 29 has % 28 parentheses % 29
This . string . has . periods
This % 3 Dstring % 3 Dhas % 3 Dequals % 3 Dsigns
This % 26 string % 26 has % 26 ampersands
This % C3 % A9string % C3 % A9has % C3 % A9non - ASCII + characters </ programlisting >
Notice in particular that this method encodes the forward slash, the ampersand, the
equals sign, and the colon. It does not attempt to determine how these characters are
being used in a URL. Consequently, you have to encode URLs piece by piece rather than
encoding an entire URL in one method call. This is an important point, because the
most common use of URLEncoder is preparing query strings for communicating with
server-side programs that use GET . For example, suppose you want to encode this URL
for a Google search:
https://www.google.com/search?hl=en&as_q=Java&as_epq=I/O
This code fragment encodes it:
String query = URLEncoder . encode (
"https://www.google.com/search?hl=en&as_q=Java&as_epq=I/O" , "UTF-8" );
System . out . println ( query );
Unfortunately, the output is:
https % 3 A % 2 F % 2 Fwww . google . com % 2 Fsearch % 3 Fhl % 3 Den % 26 as_q % 3 DJava % 26 as_epq % 3 DI % 2 FO
The problem is that URLEncoder.encode() encodes blindly. It can't distinguish between
special characters used as part of the URL or query string, like / and = , and characters
that need to be encoded. Consequently, URLs need to be encoded a piece at a time like
this:
String url = "https://www.google.com/search?" ;
url += URLEncoder . encode ( "hl" , "UTF-8" );
url += "=" ;
url += URLEncoder . encode ( "en" , "UTF-8" );
url += "&" ;
url += URLEncoder . encode ( "as_q" , "UTF-8" );
url += "=" ;
url += URLEncoder . encode ( "Java" , "UTF-8" );
url += "&" ;
url += URLEncoder . encode ( "as_epq" , "UTF-8" );
url += "=" ;
url += URLEncoder . encode ( "I/O" , "UTF-8" );
System . out . println ( url );
Search WWH ::




Custom Search