Jak odczytać odpowiedź XML z adresu URL w Javie?

Muszę napisać prostą funkcję, która pobiera adres URL i przetwarza odpowiedź, która jest XML lub JSON, sprawdziłem stronę Sun https://swingx-ws.dev.java.net/servlets/ProjectDocumentList , ale obiekt HttpRequest nigdzie nie można znaleźć, czy można to zrobić w Javie? Piszę bogatą aplikację kliencką.

Author: Karussell, 2010-02-22

7 answers

Do parsowania XML strumienia wejściowego można wykonać:

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

Ale do komunikacji przez http z serwera do klienta wolę używać hessian library lub springs http invoker lib

 73
Author: Karussell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-24 13:57:46

Jeśli chcesz wydrukować XML bezpośrednio na ekranie, możesz użyć 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));
 9
Author: thisisananth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-05 15:45:07

Uzyskaj odpowiedź poprzez zwykłe żądanie http, używając:

Następnym krokiem jest parsowanie go. Spójrz na ten artykuł , aby znaleźć wybór parsera.

 5
Author: Bozho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-22 13:42:54

Jeśli chcesz używać SwingX-WS, Spójrz na XmlHttpRequest i JSONHttpRequest.

Więcej o tych klasach w blogu XMLHttpRequest i Swing .

 2
Author: Pascal Thivent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-22 10:52:37

Ok myślę, że mam rozwiązuje problem poniżej jest kod roboczy

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


    }

}
 1
Author: Imran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-22 14:23:31

Zauważyłem, że powyższa odpowiedź spowodowała dla mnie wyjątek, gdy próbowałem utworzyć instancję parsera. Znalazłem następujący kod, który rozwiązał to w 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 ());
}
 1
Author: badMonkey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-12 22:35:00

Ten kod jest do analizy XML zawija odpowiedź JSON i wyświetlania w przedniej części za pomocą 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": "Tom", "lastName": "rejs", "Zdjęcie": " https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg " }, { "id": "2", "firstName": "Maria", "lastName": "Szarapowa", "zdjęcie": " https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg " }, { "id": "3", "firstName": "James", "lastName": "Bond", "zdjęcie": " 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);

`

 1
Author: Suneel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-06 06:20:14