siamii
siamii

Reputation: 24134

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 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?

Upvotes: 3

Views: 10001

Answers (2)

siamii
siamii

Reputation: 24134

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........

Upvotes: 4

CrackerJack9
CrackerJack9

Reputation: 3651

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.

Upvotes: -1

Related Questions