11

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;
    }
4

2 に答える 2

7

リクエストを処理してクライアントに応答した後、入力ストリームから読み取ろうとしている印象があります。コードをどこに置きましたか?

最初にリクエストを処理し、後でアンマーシャリングを行う場合は、最初に入力ストリームを文字列に読み込む必要があります。処理している小さなリクエストの場合、これはうまく機能します。

これを行うには、apache commons IOUtils のようなものを使用することをお勧めします。

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

request.getParameter(name)また、とのいずれかを選択する必要があることにも注意してくださいrequest.getInputStream。両方を使用することはできません。

于 2012-09-04T09:39:15.310 に答える
3
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();
}
于 2016-04-29T13:40:41.270 に答える