如何从Java中的URL读取XML响应?
我需要编写一个简单的函数,它接受一个URL并处理XML或JSON响应,我已经检查了Sun网站https://swingx-ws.dev.java.net/servlets/ProjectDocumentList ,但是HttpRequest对象是被发现无处可以在Java中做到这一点? 我正在写一个丰富的客户端应用程序。
对于inputstream的xmlparsing,你可以这样做:
// 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库或popuphttp调用者库
如果你想直接在屏幕上打印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 factory = TransformerFactory.newInstance(); Transformer xform = factory.newTransformer(); // that's the default xform; use a stylesheet to get a real one xform.transform(new DOMSource(doc), new StreamResult(System.out));
通过常规的http请求获取您的响应,使用:
- Apache HttpComponents
- 内置的
URLConnection con = new URL("http://example.com").openConnection()
;
下一步是parsing它。 看看这篇文章的parsing器的select。
如果你特别想使用SwingX-WS ,那么看看XmlHttpRequest和JSONHttpRequest 。
更多关于XMLHttpRequest和Swing博客文章中的这些类。
好吧,我认为我已经解决了下面的问题是一个工作代码
// package xmlhttp; import org.jdesktop.http.Response; import org.jdesktop.http.Session; import org.jdesktop.http.State; public class GetXmlHttp{ public static void main(String[] args) { getResponse(); } public static void getResponse() { final Session session = new Session(); try { String url="http://192.172.2.23:8080/geoserver/wfs?request=GetFeature&version=1.1.0&outputFormat=GML2&typeName=topp:networkcoverage,topp:tehsil&bbox=73.07846689124875,33.67929015631999,73.07946689124876,33.68029015632,EPSG:4326"; final Response res=session.get(url); boolean notDone=true; do { System.out.print(session.getState().toString()); if(session.getState()==State.DONE) { String xml=res.toString(); System.out.println(xml); notDone=false; } }while(notDone); } catch (Exception e1) { e1.printStackTrace(); } } }
当我试图实例化parsing器时,发现上面的答案导致了一个exception。 我在http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htmfind了解决这个问题的代码。;
import org.xml.sax.*; import javax.xml.parsers.*; XMLReader parser; try { SAXParserFactory factory; factory = SAXParserFactory.newInstance (); factory.setNamespaceAware (true); parser = factory.newSAXParser ().getXMLReader (); // success! } catch (FactoryConfigurationError err) { System.err.println ("can't create JAXP SAXParserFactory, " + err.getMessage ()); } catch (ParserConfigurationException err) { System.err.println ("can't create XMLReader with namespaces, " + err.getMessage ()); } catch (SAXException err) { System.err.println ("Hmm, SAXException, " + err.getMessage ()); }