【发布时间】:2013-10-24 16:11:31
【问题描述】:
我使用以下函数来检索 Web 服务响应:
private String getSoapResponse (String url, String host, String encoding, String soapAction, String soapRequest) throws MalformedURLException, IOException, Exception {
URL wsUrl = new URL(url);
URLConnection connection = wsUrl.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[soapRequest.length()];
buffer = soapRequest.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Host", host);
if (encoding == null || encoding == "")
encoding = UTF8;
httpConn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("SOAPAction", soapAction);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
InputStreamReader is = new InputStreamReader(httpConn.getInputStream());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
sb.append(read);
read = br.readLine();
}
String response = decodeHtmlEntityCharacters(sb.toString());
return response = decodeHtmlEntityCharacters(response);
}
但我对这段代码的问题是它返回大量特殊字符并使 XML 的结构无效。
示例响应:
<PLANT>A565</PLANT>
<PLANT>A567</PLANT>
<PLANT>A585</PLANT>
<PLANT>A921</PLANT>
<PLANT>A938</PLANT>
</PLANT_GROUP>
</KPI_PLANT_GROUP_KEYWORD>
<MSU_CUSTOMERS/>
</DU>
<DU>
所以为了解决这个问题,我使用以下方法并传递整个响应以将所有特殊字符替换为其对应的标点符号。
private final static Hashtable htmlEntitiesTable = new Hashtable();
static {
htmlEntitiesTable.put("&","&");
htmlEntitiesTable.put(""","\"");
htmlEntitiesTable.put("<","<");
htmlEntitiesTable.put(">",">");
}
private String decodeHtmlEntityCharacters(String inputString) throws Exception {
Enumeration en = htmlEntitiesTable.keys();
while(en.hasMoreElements()){
String key = (String)en.nextElement();
String val = (String)htmlEntitiesTable.get(key);
inputString = inputString.replaceAll(key, val);
}
return inputString;
}
但是出现了另一个问题。如果响应包含此段 &lt;VALUE&gt;&lt; 0.5 &lt;/VALUE&lt; 并且如果这将由该方法评估,则输出将是:
<VALUE>< 0.5</VALUE>
这使得 XML 的结构再次无效。 数据正确且有效“
你能帮忙解决这个问题吗?也许我获得或建立响应的方式可以改进。有没有更好的方法来调用并从 Web 服务获取响应?
如何处理包含“”的元素?
【问题讨论】:
-
所以您需要一种方法来检测“
-
我建议在 VALUE 上有一个属性。将属性设为 1 或 0,具体取决于您是否需要小于/大于。 (或 -1、0、1 表示 )
-
为什么不正确编码?
-
@BrianAgnew 它从一开始就被正确编码,与 xml 的其余部分一起。然后他在解码xml的其余部分时对其进行解码。问题是他需要区分不同的“
-
@Cruncher 嗯,它看起来不像一开始就被正确编码。如果是这样,则不会对实际的 XML 结构进行编码,而只会对数据进行编码。还是您看到了我们看不到的东西?
标签: java xml web-services