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

时间:2010-02-22 10:12:46

标签: java xml httprequest

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

8 个答案:

答案 0 :(得分:78)

对于输入流的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 library或者使用http invoker lib

答案 1 :(得分:9)

如果要直接在屏幕上打印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));

答案 2 :(得分:5)

通过常规http请求获取您的回复,使用:

下一步是解析它。请查看this article以选择解析器。

答案 3 :(得分:3)

如果您特别想使用SwingX-WS,请查看XmlHttpRequestJSONHttpRequest

XMLHttpRequest and Swing博客文章中有关这些课程的更多内容。

答案 4 :(得分:1)

好的我想我已经解决了下面的问题是一个有效的代码

//
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();
        }


    }

}

答案 5 :(得分:1)

我发现当我尝试实例化解析器时,上面的答案引起了我的异常。我发现以下代码在http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm解决了此问题。

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 ());
}

答案 6 :(得分:1)

  

此代码用于解析XML包装JSON响应并使用ajax在前端显示。

Required JavaScript code.
<script type="text/javascript">
$.ajax({
	method:"GET",
	url: "javatpoint.html", 
	
	success : function(data) { 
		
		 var json=JSON.parse(data);	
		 var tbody=$('tbody');
		for(var i in json){
			tbody.append('<tr><td>'+json[i].id+'</td>'+
					'<td>'+json[i].firstName+'</td>'+
					'<td>'+json[i].lastName+'</td>'+
					'<td>'+json[i].Download_DateTime+'</td>'+
					'<td>'+json[i].photo+'</td></tr>')
		}  
	},
	error : function () {
		alert('errorrrrr');
	}
		});
		
		</script>

[{                 “id”:“1”,                 “firstName”:“汤姆”,                 “lastName”:“巡航”,                 “照片”:“https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg”             },             {                 “id”:“2”,                 “firstName”:“Maria”,                 “lastName”:“莎拉波娃”,                 “照片”:“https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg”             },             {                 “id”:“3”,                 “firstName”:“詹姆斯”,                 “lastName”:“邦德”,                 “照片”:“https://pbs.twimg.com/profile_images/664886718559076352/M00cOLrh.jpg”             }] `

URL url=new URL("www.example.com"); 

        URLConnection si=url.openConnection();
        InputStream is=si.getInputStream();
        String str="";
        int i;
        while((i=is.read())!=-1){  
            str +=str.valueOf((char)i);
            }

        str =str.replace("</string>", "");
        str=str.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
        str = str.replace("<string xmlns=\"http://tempuri.org/\">", "");
        PrintWriter out=resp.getWriter();
        out.println(str);

`

答案 7 :(得分:1)

使用以下代码进行操作:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document doc = builder.parse("/home/codefelix/IdeaProjects/Gradle/src/main/resources/static/Employees.xml");
        NodeList namelist = (NodeList) doc.getElementById("1");

        for (int i = 0; i < namelist.getLength(); i++) {
            Node p = namelist.item(i);

            if (p.getNodeType() == Node.ELEMENT_NODE) {
                Element person = (Element) p;
                NodeList id = (NodeList) person.getElementsByTagName("Employee");
                NodeList nodeList = person.getChildNodes();
                List<EmployeeDto> employeeDtoList=new ArrayList();

                for (int j = 0; j < nodeList.getLength(); j++) {
                    Node n = nodeList.item(j);

                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element naame = (Element) n;
                        System.out.println("Employee" + id + ":" + naame.getTagName() + "=" +naame.getTextContent());
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}