3

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
siamii
  • 23,374
  • 28
  • 93
  • 143
  • 1
    Have you checked this [question](http://stackoverflow.com/questions/217070/how-do-i-add-query-parameters-to-a-getmethod-using-java-commons-httpclient), and its answers ? – MarcoS Sep 06 '11 at 05:59
  • That question refers to HttpClient 3, I'm using HttpClient 4 which is supported by Android. – siamii Sep 06 '11 at 09:45

2 Answers2

4

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

siamii
  • 23,374
  • 28
  • 93
  • 143
-1

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.

CrackerJack9
  • 3,650
  • 1
  • 27
  • 48
  • yes. maybe I misunderstood what you are looking for. If you encode the values, submit the request, then the server decodes them and can get back to the original values. – CrackerJack9 Sep 07 '11 at 13:39