【问题标题】:Characters & and < make everything get lost on the way between HttpPost and HttpResponse字符 & 和 < 让一切在 HttpPost 和 HttpResponse 之间迷路
【发布时间】:2012-10-25 14:51:28
【问题描述】:

我将一些 XML 作为 SOAP 请求发送,但是当该 XML 包含字符 &amp;&lt; 时,我得到一个空响应。以下是一些相关代码:

String myXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
               "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
                   "<soap12:Body>" +
                      "[XML THAT DOESN'T WORK WITH '&' AND '<']" +
                   "</soap12:Body>" +
               "</soap12:Envelope>";

HttpPost httpPost = new HttpPost("http://website.com");
StringEntity stringEntity = new StringEntity(myXml, HTTP.UTF_8);
stringEntity.setContentType("text/xml");
httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8)";
httpPost.setEntity(stringEntity);

HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient.execute(httpPost);

HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = responseEntity.getContent();
//Checking inputStream here reveals that it is empty (not null) when xml has '&' or '<'

我认为这可能是因为these predefined entities,但我尝试过的所有其他特殊字符都没有引起任何问题。

您知道这是为什么,以及我该如何解决它(除了捕捉&amp;&lt; 的具体情况)?

我找到了建议的解决方案

httpPost.setEntity(new UrlEncodedFormEntity(List<NameValuePair>, String encoding))

但我没有NameValuePairs,只有StringEntity

【问题讨论】:

  • xml 明确不支持 和 &。这 3 个实体必须被转义。例如,您可以使用 URLEncoder.encode(但它会编码更多的东西,您可能会遇到这些问题)。
  • 不只是三个,它们是 5(你没有提到撇号和双引号)。
  • URLEncoder.encode 不适用于 xml 数据转义。
  • @Arhimed 出于某种原因, > 和 ' 和 " 不会在我的应用程序中引起问题。它只是
  • 好吧,我们正在谈论 xml 规范,它指出应该转义这 5 个。我相信,你不会对所有特殊字符都产生问题,这只是一个快乐的极端情况。

标签: android http-post special-characters httpresponse


【解决方案1】:

我认为可能是因为这些预定义的实体

没错。这些值应该被转义,所以正确的数据版本是:

[XML THAT DOESN'T WORK WITH '&amp;' AND '&lt;']

【讨论】:

  • 在维基百科页面上,我应该查看 XML 列表还是 HTML 列表?如果是 XML 列表,我想我会创建一个函数来捕获这五个字符。
  • 是的,只需创建一个“过滤器”函数,用它们的转义版本替换所有出现的这 5 个字符。
  • 您也可以尝试使用 Android API 中的XmlSerializer。例如,它的text(String text) 写入文本,其中特殊的 XML 字符会自动转义。但我认为实现自己的自定义过滤器解决方案比学习如何正确使用XmlSerializer 更快。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 2021-06-23
相关资源
最近更新 更多