我正在尝试使用Java Servlet创建RESTful Web服务.问题是我必须通过POST方法传递给Web服务器请求.此请求的内容不是参数,而是正文本身.
所以我基本上从ruby发送这样的东西:
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 }
然后我必须在我的servlet中检索此请求的主体.我使用经典的readline,所以我有一个字符串.问题是我必须将其解析为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()); } }
问题是,builder.parse()
接受:parse(File f)
,parse(InputSource is)
,parse(InputStream is)
.
有什么方法可以在InputSource中转换我的xml字符串或类似的东西?我知道这可能是一个虚假的问题,但Java不是我的事,我被迫使用它而且我不是很熟练.
您可以通过StringReader从字符串创建InputSource:
Document doc = builder.parse(new InputSource(new StringReader(soft)));