Imr*_*ran 45 java xml httprequest
我需要编写一个简单的函数,它接受一个URL并处理XML或JSON的响应,我已经检查了Sun网站https://swingx-ws.dev.java.net/servlets/ProjectDocumentList,但是HttpRequest对象是无处可寻,有可能用Java做到这一点吗?我正在写一个富客户端应用程序.
Kar*_*ell 79
对于输入流的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());
Run Code Online (Sandbox Code Playgroud)
但是要通过http从服务器到客户端进行通信,我更喜欢使用粗体库或spring http invoker lib
如果要直接在屏幕上打印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));
Run Code Online (Sandbox Code Playgroud)
通过常规http请求获取您的回复,使用:
URLConnection con = new URL("http://example.com").openConnection();下一步是解析它.看一下这篇文章,选择解析器.