Java Reference
In-Depth Information
Example 5-7 is a program that uses URLEncoder.encode() to print various encoded
strings.
Example 5-7. x-www-form-urlencoded strings
import java.io.* ;
import java.net.* ;
public class EncoderTest {
public static void main ( String [] args ) {
try {
System . out . println ( URLEncoder . encode ( "This string has spaces" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This*string*has*asterisks" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This%string%has%percent%signs" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This+string+has+pluses" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This/string/has/slashes" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This\"string\"has\"quote\"marks" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This:string:has:colons" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This~string~has~tildes" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This(string)has(parentheses)" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This.string.has.periods" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This=string=has=equals=signs" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "This&string&has&ampersands" ,
"UTF-8" ));
System . out . println ( URLEncoder . encode ( "Thiséstringéhasé
non-ASCII characters" , "UTF-8" ));
} catch ( UnsupportedEncodingException ex ) {
throw new RuntimeException ( "Broken VM does not support UTF-8" );
}
}
}
Here is the output (note that the code needs to be saved in something other than ASCII,
and the encoding chosen should be passed as an argument to the compiler to account
for the non-ASCII characters in the source code):
% javac - encoding UTF8 EncoderTest
% java EncoderTest
This + string + has + spaces
Search WWH ::




Custom Search