如何在java中从URL读取XML响应?

2022-08-31 22:23:41

我需要编写一个简单的函数来获取URL并处理XML或JSON的响应,我已经检查了Sun网站 https://swingx-ws.dev.java.net/servlets/ProjectDocumentList,但是HttpRequest对象无处可寻,是否可以在Java中执行此操作?我正在编写一个富客户端应用。


答案 1

对于输入流的 xml 解析,您可以执行以下操作:

// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));

// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());

但是要通过http从服务器到客户端进行通信,我更喜欢使用Hessian库或spring http invoker lib


答案 2

如果你想直接将XML打印到屏幕上,你可以使用TransformerFactory。

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());

TransformerFactory transformerFactory= TransformerFactory.newInstance();
Transformer xform = transformerFactory.newTransformer();

// that’s the default xform; use a stylesheet to get a real one
xform.transform(new DOMSource(doc), new StreamResult(System.out));

推荐