Reputation: 1199
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)
I tried the following code to unmarshall the HttpServletRequest
.
InputStreamReader is =
new InputStreamReader(request.getInputStream());
InputStream isr = request.getInputStream();
ServletInputStream req = request.getInputStream();
My parser method:
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;
}
Upvotes: 13
Views: 34881
Reputation: 1078
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();
}
Upvotes: 3
Reputation: 17435
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.
I suggest using something like apache commons IOUtils to do this for you.
String marshalledXml = org.apache.commons.io.IOUtils.toString(request.getInputStream());
Also keep in mind that you have to choose between request.getParameter(name)
and request.getInputStream
. You can't use both.
Upvotes: 7