2012-09-05 89 views
1

我從客戶端獲取HttpservletRequest,我試圖解析請求(使用JAXB,DOM)。對於我使用下面的代碼InputStream異常解析

String str_request = IOUtils.toString(request.getInputStream()); 
System.out.println("String is " + str_request); 
requestStream = new ByteArrayInputStream(str_request.getBytes()); 

我的問題是,當我的requestStream傳遞給我的解析器方法,一種方法是工作正常,但另一種失敗。我猜這是inputStream的問題,但我無法解決這個問題。任何人都可以爲這個問題提出解決方案。

DOM解析器方法:

public String parseMethodName(InputStream request) throws SAXException, 
                  IOException, 
                  ParserConfigurationException { 

    System.out.println("in parseMethodName"); 
    DocumentBuilderFactory dbFactory = 
     DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
    System.out.println("bfor parse"); 
    Document doc = dBuilder.parse(request); 
    System.out.println("After parse"); 
    methodName = 
      doc.getElementsByTagName("methodName").item(0).getTextContent(); 
} 

JAXB解析器方法:

System.out.println("in parse ******"); 
JAXBContext context = JAXBContext.newInstance(MethodCall.class); 
System.out.println("bfor unmarshall ****"); 
Unmarshaller um = context.createUnmarshaller(); 
System.out.println("After unmarshall ****"); 
mc = (MethodCall) um.unmarshal(is); 

我收到以下異常:

javax.xml.bind.UnmarshalException 
- with linked exception: 
[org.xml.sax.SAXParseException: Premature end of file.] 
     at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315) 
     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:481) 
     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:199) 
     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:168) 
     at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137) 
     at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:184) 

回答

3

你不應該輸入流轉換爲一個字符串,然後返回到一個字節數組。這只是要求丟失數據,尤其是在將字符串轉換爲字節數組時使用平臺默認編碼。

看看無論你正在使用IOUtils類包含一個方法只是完全讀取InputStreambyte[],並使用該爲您ByteArrayInputStream的基礎。

請注意,如果要多次讀取數據,您需要重置流,或者在同一個字節數組周圍創建新流。