2013-03-20 19 views
1

我們正在將功能從Weblogic服務器8,1 sp5(使用java 1.4)遷移到使用java 1.7的10.3.6。在Weblogic中解析SOAP調用的XML響應

下面介紹的情況在舊服務器上正常工作,但是在將處理轉移到新服務器時我們遇到了問題。 問題在於檢索和解析通過SOAP調用從外部系統檢索到的XML響應。

以下庫和過程中的方法中,使用:

  1. java.net.HttpURLConnection中進行連接
  2. java.io.OutputStream中發送請求
  3. java.io.InputStream得到迴應
  4. 字節[]將結果存儲在變換到字符串
  5. javax.xml.parsers.DocumentBuilder中java.io.StringReader中org.xml.sax.InputSource中以變換前的字符串到org.w3c.dom.Document中
  6. 下拋出異常: 「org.xml.sax.SAXParseException - 內容是不允許在尾隨分節。」

當記事本++許多空字符打開應用程序的日誌文件的末尾,這似乎導致問題出現後。我再說一遍,在執行舊服務器請求時不會出現這種情況。

相應的代碼如下:

//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版本問題或者服務器配置問題? 預先感謝您的時間。

最好的問候, 喬治

回答

1

我看到兩個問題

  • in.available()按的Javadoc:返回一個估計字節數的 ...不要依賴此。在8K的緩衝區上循環讀取流,直到您達到最終效果或者更好,不要重新發明輪子,使用Apache的commons-io並使用一個單一的調用來呼叫ÌOUtils.read
  • String response = new String(r);這樣做,您假設接收到的字節使用與平臺編碼/字符集相同的字符集進行編碼。如果您在Windows或OSX上,則情況不太可能如此。您必須通過字符集並使用構造函數String(byte[] bytes, Charset charset)
+0

非常有幫助的回覆。我不明白爲什麼這個問題只出現在新環境中,但似乎問題是從in.available()中估計長度。非常感謝您的指示! – georgeM 2013-03-20 16:44:28

+0

然後請接受回覆;這對你的法師很好 – 2013-03-20 16:45:09