问题遇到的现象和发生背景
dom4j SAXReader.read无法解析微信公众号post请求中request.getInputstream
报Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; 文件提前结束。异常
问题相关代码,请勿粘贴截图
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("用户发送post请求");
ServletInputStream is = request.getInputStream();
byte[] b=new byte[1024];
int len;
StringBuilder sb=new StringBuilder();
while ((len= is.read(b))!=-1){
sb.append(new String(b,0,len));
}
System.out.println(sb.toString());
Map<String,String> map=WxService.parseRequest(request.getInputStream());
if (map==null){
System.out.println("出现异常");
}else{
System.out.println(map);
}
}
public static Map<String, String> parseRequest(ServletInputStream inputStream) {
Map<String, String> map = null;
SAXReader reader = new SAXReader() ;
try {
map=new HashMap<>();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> eLements =root.elements();
for (Element eLement : eLements) {
map.put(eLement.getName(),eLement.getStringValue());
}
return map;
} catch (DocumentException e) {
e.printStackTrace();
e.getMessage();
return null;
}
}