0

Header Request

POST http://{URL} HTTP/1.1
Accept: */*
Accept-Language: en-us
Content-Type: text/xml; charset=UTF-8
Accept-Encoding: gzip, deflate
Content-Length: 1049
Connection: Keep-Alive
Pragma: no-cache
<?xml version="1.0"?>
 <userID>dummy</userID>
<password>pwd</password>

I have the above request which is send to a ServletRequest in doFilter. I am able to read parameters by using servet apis as below

HttpServletRequest req = (HttpServletRequest) request;
Enumeration<String> params = req.getParameterNames();

How can I read the xml content inorder to retrieve UserID in that xml using servlet in Java

Vinay Katta
  • 27
  • 2
  • 5
  • I wonder if that's a real user and password – wRAR Aug 13 '14 at 06:27
  • http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getInputStream%28%29. Note that what you have there is not valid XML. An XML document has a single root element. – JB Nizet Aug 13 '14 at 06:33
  • possible duplicate of [Java: How to read and write xml files?](http://stackoverflow.com/questions/7373567/java-how-to-read-and-write-xml-files) – Raedwald Aug 13 '14 at 06:59

1 Answers1

0

This is how I did to read the XML into a map from HTTPServletRequest using org.dom4j.io.SAXReader

public  static Map<String, String>  parseXml(HttpServletRequest request) throws    IOException, DocumentException {
    Map<String,String> map=new HashMap<String,String>();
    InputStream is =request.getInputStream();
    SAXReader reader=new SAXReader();
    Document document=reader.read(is);      
    Element root =document.getRootElement();

    List<Element> elementList=root.elements();

    for(Element e: elementList){
        map.put(e.getName(), e.getText());
    }

    //now your map will have below mapping 
    //"userID"->"dummy"
    //"password"->"pwd"

    return map;     
}
JaskeyLam
  • 15,405
  • 21
  • 114
  • 149