我怎样才能转换HttpServletRequest为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)
Run Code Online (Sandbox Code Playgroud)
我尝试了以下代码来解组HttpServletRequest.
InputStreamReader is =
new InputStreamReader(request.getInputStream());
InputStream isr = request.getInputStream();
ServletInputStream req = request.getInputStream();
Run Code Online (Sandbox Code Playgroud)
我的解析器方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
在您处理完请求并回复客户端后,我的印象是您尝试从输入流中读取.你把代码放在哪里了?
如果要先处理请求,然后再进行解组,则需要先将输入流读入String.如果您处理的请求很小,这样可以正常工作.
我建议使用像apache commons IOUtils这样的东西为你做这个.
String marshalledXml = org.apache.commons.io.IOUtils.toString(request.getInputStream());
Run Code Online (Sandbox Code Playgroud)
另请注意,您必须在request.getParameter(name)和之间进行选择request.getInputStream.你不能同时使用它们.