【发布时间】:2012-10-25 14:51:28
【问题描述】:
我将一些 XML 作为 SOAP 请求发送,但是当该 XML 包含字符 & 或 < 时,我得到一个空响应。以下是一些相关代码:
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,但我尝试过的所有其他特殊字符都没有引起任何问题。
您知道这是为什么,以及我该如何解决它(除了捕捉& 和< 的具体情况)?
我找到了建议的解决方案
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