Apache HttpGet url encoding problem (plus sign, +)
I'm sending a GET request with HttpClient but the +
is not encoded.
1.
If I pass the query
parameter string unencoded like this
URI uri = new URI(scheme, host, path, query, null);
HttpGet开发者_Go百科 get = new HttpGet(uri);
Then the +
sign is not encoded and it is received as a space on the server. The rest of the url is encoded fine.
2.If I encode the parameters in the query
string like this
param = URLEncoder.encode(param,"UTF-8");
Then I get a bunch of weird symbols on the server, probably because the url has been encoded twice.
3.If I only replace the +
with %B2
like this
query = query.replaceAll("\\+","%B2");
Then %B2
is encoded when the GET is executed by HttpClient
How can I properly encode Get parameters with Apache HttpClient and make sure the +
is encoded as well?
Ok, the solution was that instead of creating the URI like this
URI uri = new URI(scheme, host, path, query, null);
One should create it like this
URIUtils.createURI(scheme, host, -1, path, query, null);
The purpose of the URIUtils class is
A collection of utilities for URIs, to workaround bugs within the class
no comment........
When you build the query
string, use URLEncoder.encode(paramValue, "UTF-8")
for each parameter value. Then when you send the request, use URLDecoder.decode(paramValue, "UTF-8")
and the "weird symbols" will be decoded.
精彩评论