18

I'm trying to create a RESTful webservice using a Java Servlet. The problem is I have to pass via POST method to a webserver a request. The content of this request is not a parameter but the body itself.

So I basically send from ruby something like this:

url = URI.parse(@host)
req = Net::HTTP::Post.new('/WebService/WebServiceServlet')
req['Content-Type'] = "text/xml"
# req.basic_auth 'account', 'password'
req.body = data
response = Net::HTTP.start(url.host, url.port){ |http| puts http.request(req).body }

Then I have to retrieve the body of this request in my servlet. I use the classic readline, so I have a string. The problem is when I have to parse it as XML:

private void useXML( final String soft, final PrintWriter out) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, FileNotFoundException {
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  domFactory.setNamespaceAware(true); // never forget this!
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse(soft);

  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  XPathExpression expr = xpath.compile("//software/text()");

  Object result = expr.evaluate(doc, XPathConstants.NODESET);
  NodeList nodes = (NodeList) result;
  for (int i = 0; i < nodes.getLength(); i++) {
    out.println(nodes.item(i).getNodeValue()); 
  }
}

The problem is that builder.parse() accepts: parse(File f), parse(InputSource is), parse(InputStream is).

Is there any way I can transform my xml string in an InputSource or something like that? I know it could be a dummy question but Java is not my thing, I'm forced to use it and I'm not very skilled.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
dierre
  • 7,140
  • 12
  • 75
  • 120
  • Thank you Dimitre for the editing. I'm getting used to this format code. – dierre May 17 '10 at 17:55
  • Can you post sample XML that works with this code? I am working on a similar design and my node, following the xpath query is coming back null, so I suspect my xpath expression or my xml is not well-formed. – mobibob Aug 20 '10 at 13:13

2 Answers2

53

You can create an InputSource from a string by way of a StringReader:

Document doc = builder.parse(new InputSource(new StringReader(soft)));
Don Roby
  • 40,677
  • 6
  • 91
  • 113
3

With your string, use something like :

ByteArrayInputStream input = 
 new ByteArrayInputStream(yourString.getBytes(perhapsEncoding));
builder.parse(input);

ByteArrayInputStream is an InputStream.

Istao
  • 7,425
  • 6
  • 32
  • 39