如何将HttpServletRequest转换为String?

时间:2012-09-04 09:30:38

标签: java servlets

如何将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)

我尝试使用以下代码来解组​​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;
    }

2 个答案:

答案 0 :(得分:5)

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

如果要先处理请求,稍后再进行解组,则需要先将输入流读入String。如果您正在处理的请求很少,这样可以正常工作。

我建议使用像apache commons IOUtils这样的东西为你做这件事。

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

另请注意,您必须在request.getParameter(name)request.getInputStream之间进行选择。你不能同时使用它们。

答案 1 :(得分:1)

String httpServletRequestToString(HttpServletRequest request) throws Exception {

    ServletInputStream mServletInputStream = request.getInputStream();
    byte[] httpInData = new byte[request.getContentLength()];
    int retVal = -1;
    StringBuilder stringBuilder = new StringBuilder();

    while ((retVal = mServletInputStream.read(httpInData)) != -1) {
        for (int i = 0; i < retVal; i++) {
            stringBuilder.append(Character.toString((char) httpInData[i]));
        }
    }

    return stringBuilder.toString();
}