How to convert an HttpServletRequest to String?

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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

回答1:

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.



回答2:

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(); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!