【问题标题】:How to encode space as %20 in UrlEncodedFormEntity while executing apache HttpPost?执行 apache HttpPost 时如何在 UrlEncodedFormEntity 中将空间编码为 %20?
【发布时间】:2011-10-27 11:10:16
【问题描述】:

我访问的网络服务需要 URLEncodedFormEntity 形式的参数。我无法根据 Web 服务的要求将空间更改为 %20,而是将空间转换为 +。

我的代码是:

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);

其中参数是List<NameValuePair> 参数。

我阅读了很多帖子,都建议在编码后手动将空间更改为 %20。在这里,我如何访问实体并手动更改它? 任何帮助将不胜感激。

【问题讨论】:

    标签: android apache encoding httpclient url-encoding


    【解决方案1】:

    UrlEncodedFormEntity 基本上是一个带有自定义构造函数的 StringEntity,您实际上不必使用它来创建可用的实体。

    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
    

    【讨论】:

    • 感谢您的回复。您能帮我一下吗?假设我需要发送一个名称值对: itemName = Potato Chips 我需要如何修改并将其添加到实体?
    • 尝试将带有“itemName”和“Potato Chips”的新 BasicNameValuePair 添加到参数中,然后执行 entityValue.replaceAll("\\+","%20");我在哪里写 // 在 entityValue 中进行替换。
    • 其实可以使用URLEncoder对参数的每个值进行编码,然后在实体创建中使用。
    • fyi:URLEncoder 将用 + 替换 HSPACE,因为 Rahul 想避免 - 所以你仍然需要用 %20 替换它们。
    【解决方案2】:

    Jens 的回答很有魅力!为了完成他的示例,这是我用来发布参数的:

    String label = "A label";
    
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    
    nvps.add(new BasicNameValuePair("label", label));
    httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    

    但它总是发布“+”字符串,我的意思是“label=A+label”。根据 Jens 的建议,我将代码更改为:

    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);
    

    现在它发布“label=A%20label”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2016-04-25
      • 2011-02-10
      相关资源
      最近更新 更多