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

后端 未结 2 871
北荒
北荒 2021-01-01 06:24

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 conve

2条回答
  •  心在旅途
    2021-01-01 06:39

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

    String label = "A label";
    
    List nvps = new ArrayList();
    
    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 nvps = new ArrayList();
    
    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"

提交回复
热议问题