如何将 HttpServletRequest 转换为字符串?

2023-12-21

我怎样才能转换HttpServletRequest to String?我需要解组HttpServletRequest但是当我尝试这样做时,我的程序会抛出异常。

 javax.xml.bind.UnmarshalException
 - with linked exception:
[java.io.IOException: Stream closed]
        at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:197)
        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)
        at com.orange.oapi.parser.XmlParsing.parse(XmlParsing.java:33)

我尝试使用以下代码来解组HttpServletRequest.

InputStreamReader is =
                new InputStreamReader(request.getInputStream());
InputStream isr = request.getInputStream();
ServletInputStream req = request.getInputStream();

我的解析器方法:

public root parse(InputStreamReader is) throws Exception {
        root mc = null;
        try {
            JAXBContext context = JAXBContext.newInstance(root.class);
            Unmarshaller um = context.createUnmarshaller();
            mc = (root) um.unmarshal(is);
        } catch (JAXBException je) {
            je.printStackTrace();
        }
        return mc;
    }

我的印象是,在处理请求并响应客户后,您尝试从输入流中读取内容。你把你的代码放在哪里了?

如果您想先处理请求,然后再进行解组,则需要先将输入流读入字符串。如果您正在处理的请求很小,那么这很有效。

我建议使用 apache commons IOUtils 之类的东西来为您做到这一点。

String marshalledXml = org.apache.commons.io.IOUtils.toString(request.getInputStream());

另请记住,您必须在以下两者之间做出选择request.getParameter(name) and request.getInputStream。你不能同时使用两者。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 HttpServletRequest 转换为字符串? 的相关文章

随机推荐