Skip to content Skip to sidebar Skip to footer

How To Encode Space As %20 In Urlencodedformentity While Executing Apache Httppost?

The web serive i am hitting requires the parameters as URLEncodedFormEntity. I am unable to change space to %20 as per requirement of the web service, instead space is converted to

Solution 1:

The UrlEncodedFormEntity is basically a StringEntity with a custom constructor, you don't actually have to use it in order to create a usuable entity.

StringentityValue= URLEncodedUtils.format(parameters, HTTP.UTF_8);
// Do your replacement here in entityValueStringEntityentity=newStringEntity(entityValue, HTTP.UTF_8);
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
// And now do your posting of this entity

Solution 2:

Jens' answer works like a charm!. To complete his example this what I was using to post a parameter:

String label = "A label";

List<NameValuePair> nvps = new ArrayList<NameValuePair>();

nvps.add(new BasicNameValuePair("label", label));
httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

But it always posts the "+" string, I mean, "label=A+label". Using Jens' suggestion I changed my code to:

Stringlabel="A label";

List<NameValuePair> nvps = newArrayList<NameValuePair>();

nvps.add(newBasicNameValuePair("label", label));

StringentityValue= URLEncodedUtils.format(nvps, HTTP.UTF_8);
entityValue = entityValue.replaceAll("\\+", "%20");

StringEntitystringEntity=newStringEntity(entityValue, HTTP.UTF_8);
stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);

httpget.setEntity(stringEntity);

Now it posts "label=A%20label"

Post a Comment for "How To Encode Space As %20 In Urlencodedformentity While Executing Apache Httppost?"