![](/img/trans.png)
[英]How to convert HttpServletRequest to a corresponding HttpClient object
[英]How to convert an HttpServletRequest to String?
如何將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;
}
在您處理完請求並回復客戶端后,我的印象是您嘗試從輸入流中讀取。 你把代碼放在哪里了?
如果要先處理請求,然后再進行解組,則需要先將輸入流讀入String。 如果您處理的請求很小,這樣可以正常工作。
我建議使用像apache commons IOUtils這樣的東西為你做這個。
String marshalledXml = org.apache.commons.io.IOUtils.toString(request.getInputStream());
還要記住,您必須在request.getParameter(name)
和request.getInputStream
之間進行選擇。 你不能同時使用它們。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.