如何将HttpServletRequest转换为String? [英] How to convert an HttpServletRequest to String?
问题描述
如何将 HttpServletRequest
转换为 String
?我需要解组 HttpServletRequest
但是当我尝试时,我的程序会抛出异常。
How can I convert an HttpServletRequest
to String
? I need to unmarshall the HttpServletRequest
but when I try to, my program throws an exception.
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;
}
推荐答案
我的印象是你'在处理完请求并响应客户端后,尝试读取输入流。你把代码放在哪里了?
I have the impression you're trying to read from the input stream after you've handled the request and responded to your client. Where did you put your code?
如果你想先处理请求,然后再进行解组,你需要先将输入流读入一个字符串。如果你正在处理小请求,这样可以正常工作。
If you want to handle the request first, and do the unmarshalling later, you need to read the inputstream into a String first. This works fine if it's small requests you're handling.
我建议使用像apache commons IOUtils这样的东西为你做这个。
I suggest using something like apache commons IOUtils to do this for you.
String marshalledXml = org.apache.commons.io.IOUtils.toString(request.getInputStream());
另请注意,您必须在 request.getParameter(名称)之间进行选择)
和 request.getInputStream
。你不能同时使用它们。
Also keep in mind that you have to choose between request.getParameter(name)
and request.getInputStream
. You can't use both.
这篇关于如何将HttpServletRequest转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!