我们正在将功能从带有 java 1.4 的 Weblogic Server 8,1 sp5 迁移到带有 java 1.7 的 10.3.6。
下面描述的情况在旧服务器中运行正常,但是我们在将处理转移到新服务器时遇到问题。 问题在于检索和解析通过 SOAP 调用从外部系统检索的 XML 响应。
该方法中使用了以下库和过程:
- java.net.HttpURLConnection 建立连接
- java.io.OutputStream发送请求
- java.io.InputStream 获取响应
- byte[] 在转换为String之前存储结果
- javax.xml.parsers.DocumentBuilder、java.io.StringReader 和 org.xml.sax.InputSource 将字符串转换为 org.w3c.dom.Document
- 抛出以下异常: “org.xml.sax.SAXParseException - 尾随部分中不允许有内容。”
使用 Notepad++ 打开应用程序的日志时,文件末尾后出现许多空字符,这似乎导致了问题。我再说一遍,在旧服务器执行请求时不会出现这种情况。
相应的代码如下:
//Creating the connection
URL u = new URL(default_server);
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("SOAPAction", soap_action);
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
wout.write(xmlString);
wout.flush();
wout.close();
InputStream in = connection.getInputStream();
int c = in.available();
byte r[] = new byte[c];
in.read(r);
String response = new String(r);
connection.disconnect();
//Transorming the String to XML Doc
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader theReader = new StringReader(response);
InputSource theInputSource = new InputSource();
theInputSource.setCharacterStream(theReader);
Document doc = builder.parse(theInputSource);
//Here occurs org.xml.sax.SAXParseException-Content is not allowed in trailing section
return doc;
我知道我可以通过从垃圾字符中剥离响应来解决问题,但这不是一个安全的解决方案。 中方是否有关于此事可以分享的信息?您认为这是java版本问题还是服务器配置问题? 预先感谢您的宝贵时间。
最诚挚的问候, 乔治
最佳答案
我看到两个问题
in.available()
根据 javadoc:返回字节数的估计...不要依赖于此。循环 8K 的缓冲区来读取流,直到到达末尾,甚至更好,不要重新发明轮子,使用 Apache 的 commons-io 并使用对ÌOUtils.read
的单次调用String response = new String(r);
这样做,您假设接收到的字节是使用与您的平台编码/字符集相同的字符集进行编码的。如果您使用的是 Windows 或 OSX,则不太可能出现这种情况。您必须传递字符集并使用构造函数String(byte[] bytes, Charset charset)
。
关于java - 在Weblogic中解析SOAP调用的XML响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15524313/