java - 解析时 InputStream 异常

标签 java

我从客户端收到一个 HttpservletRequest,我正在尝试解析请求(使用 JAXB、DOM)。为此,我正在使用以下代码

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)

最佳答案

您不应该将输入流转换为字符串,然后再转换回字节数组。这只是要求丢失数据,尤其是当您在将字符串转换为字节数组时使用平台默认编码时。

查看您正在使用的哪个 IOUtils 类是否包含一个方法来将 InputStream 完全读取为 byte[],然后使用作为您的 ByteArrayInputStream 的基础。

请注意,如果您想多次读取数据,则需要重置流,或者围绕同一字节数组创建一个新流。

关于java - 解析时 InputStream 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12278062/

相关文章:

java - 如何检测 Java 中 if else 语句中的所有特殊字符?

java - java中的GSON解析器打印null

java - 如何在Activiti7中使用 "IdentityService and FormService"

java - 如何使用 Java Jersey 对路径参数进行编码

java - 如何计算处理中两个因变量之间的距离?

java - 为什么 WatchService 使用未绑定(bind)的通配符 WatchEvent<?> 而不是 WatchEvent<Path>

java - Grails JUnit 测试用例,不执行标有 @BeforeClass 注释的方法

java - Solaris 中的 Log4j 多线程

java - 更好地理解错误 : Scope 'session' is not active for the current thread

java - exec() 在 Debian 7 上不起作用