Java Reference
In-Depth Information
The output of this is what you actually want:
https:
//www.google.com/search?hl=en&as_q=Java&as_epq=I/O
In this case, you could have skipped encoding several of the constant strings such as
“Java” because you know from inspection that they don't contain any characters that
need to be encoded. However, in general, these values will be variables, not constants;
and you'll need to encode each piece to be safe.
Example 5-8
is a
QueryString
class that uses
URLEncoder
to encode successive name
and value pairs in a Java object, which will be used for sending data to server-side
programs. To add name-value pairs, call the
add()
method, which takes two strings as
arguments and encodes them. The
getQuery()
method returns the accumulated list of
encoded name-value pairs.
Example 5-8. The QueryString class
import
java.io.UnsupportedEncodingException
;
import
java.net.URLEncoder
;
public
class
QueryString
{
private
StringBuilder
query
=
new
StringBuilder
();
public
QueryString
()
{
}
public
synchronized
void
add
(
String
name
,
String
value
)
{
query
.
append
(
'&'
);
encode
(
name
,
value
);
}
private
synchronized
void
encode
(
String
name
,
String
value
)
{
try
{
query
.
append
(
URLEncoder
.
encode
(
name
,
"UTF-8"
));
query
.
append
(
'='
);
query
.
append
(
URLEncoder
.
encode
(
value
,
"UTF-8"
));
}
catch
(
UnsupportedEncodingException
ex
)
{
throw
new
RuntimeException
(
"Broken VM does not support UTF-8"
);
}
}
public
synchronized
String
getQuery
()
{
return
query
.
toString
();
}
@Override
public
String
toString
()
{
return
getQuery
();
}
}