2015-12-21 72 views
-1

我有一個Play網絡應用程序向服務器發出HTTP請求。Play Framework:解析服務器的響應,因爲Xml返回null文檔

請求進行得很順利:我收到一個200狀態碼和Content-type =「application/xml」的響應。

如果我打印stdout響應正文,我看到一個格式良好的Xml文檔。

但是,如果我嘗試使用WSResponse.asXml()從響應 創建org.w3c.dom.XML文檔,該方法返回一個空文檔。

這是我的代碼的相關部分:

private WSResponse sendPostRequest(String url, String body) { 

    WSRequest request = WS.url(url); 

    request.setHeader("Content-type", "application/x-www-form-urlencoded"); 

    return request.post(body).get(5000L); 
} 

和:

public Result requestDefaultImport() { 

    String url = "some_url"; 
    String body = "some_body"; 

    WSResponse response = sendPostRequest(url, body); 

    System.out.println(response.getBody()); //prints well-formed Xml 

    Document xmld = response.asXml(); 
    System.out.println(xmld); //prints: #[null document] 


    return ok(); 
} 

我在做什麼錯?

+0

能否請您告訴我們您的代碼嗎?您使用的確切代碼。 – Jagrut

+0

是的,我附加了代碼。 – Eduard

+0

嘗試打印'System.out.println(response.asXml());'。如果打印正確,則可能需要創建DocumentFactory對象並使用該對象來創建Document。 – Jagrut

回答

0

試試這個代碼:

Document doc = request().body().asXml(); 
Source source = new DOMSource(doc); 
StringWriter stringWriter = new StringWriter(); 
StreamResult result = new StreamResult(stringWriter); 
TransformerFactory factory = TransformerFactory.newInstance(); 
javax.xml.transform.Transformer transformer = factory.newTransformer(); 
transformer.transform(source, result); 
String xmlStr = stringWriter.getBuffer().toString(); 
System.out.println(xmlStr); 

或者這一點,如果從SOAP消耗:

Document doc = soapBody.extractContentAsDocument(); 
Source source = new DOMSource(doc); 
StringWriter stringWriter = new StringWriter(); 
Result result = new StreamResult(stringWriter); 
TransformerFactory factory = TransformerFactory.newInstance(); 
Transformer transformer = factory.newTransformer(); 
transformer.transform(source, result); 
strSoapBody = stringWriter.getBuffer().toString();