How to encode space as %20 in UrlEncodedFormEntity while executing apache HttpPost?

久未见 提交于 2019-11-29 16:01:55

问题


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

My code is :

HttpClient client = new DefaultHttpClient()
HttpPost post = new HttpPost(url);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
            HTTP.UTF_8);
post.setEntity(entity);
HttpResponse resp = client.execute(post);

where parameters is List<NameValuePair> parameters.

I read through many posts and all suggest manuall change space to %20 after emcoding. Here, how do i access the entity and change it manually? Any help will be appreciated.


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

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



回答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:

String label = "A label";

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

nvps.add(new BasicNameValuePair("label", label));

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

StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);

httpget.setEntity(stringEntity);

Now it posts "label=A%20label"



来源:https://stackoverflow.com/questions/7915029/how-to-encode-space-as-20-in-urlencodedformentity-while-executing-apache-httppo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!