48

I need to write a simple function that takes a URL and processes the response which is XML or JSON, I have checked the Sun website https://swingx-ws.dev.java.net/servlets/ProjectDocumentList , but the HttpRequest object is to be found nowhere, is it possible to do this in Java? I`m writting a rich client end app.

Karussell
  • 17,085
  • 16
  • 97
  • 197
Imran
  • 847
  • 2
  • 9
  • 9

8 Answers8

85

For xml parsing of an inputstream you can do:

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

But to communicate over http from server to client I prefer using hessian library or springs http invoker lib

Karussell
  • 17,085
  • 16
  • 97
  • 197
  • thankyou for your reply, Im getting the response into a DOM and I`m getting heapspace error at : final Response res=session.get(url); the xml response is quite large, any idea how to get rid of this? – Imran Feb 24 '10 at 12:22
  • 5
    yes, DOM reads all the stuff into memory. So either you should use sax api or increase heapspace via -Xmx512m. There are other options as well e.g. with pull parsers. – Karussell Feb 24 '10 at 13:57
11

If you want to print XML directly onto the screen you can use 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));
thisisananth
  • 398
  • 6
  • 17
5

Get your response via a regular http-request, using:

The next step is parsing it. Take a look at this article for a choice of parser.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Hi thanks for your reply, I did check a few parsers but the problem is that I cannot seem to find a bridge between these parsers and an xml response from a URL, all the parsers talk about files and nobody talks about an inputstream hooked on to a URL – Imran Feb 22 '10 at 10:44
  • 1
    @Imran they all accept input-streams as well, just look at their API docs – Bozho Feb 22 '10 at 10:52
3

If you specifically want to use SwingX-WS, then have a look at XmlHttpRequest and JSONHttpRequest.

More on those classes in the XMLHttpRequest and Swing blog post.

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • Hi thanks, well I did try this code out, It looks very simple and easy but I downloaded and included the library and I cannot find the HttpRequest object in the Libraries, that is so strange – Imran Feb 22 '10 at 10:57
  • @Imran I think that `HttpRequest` has been removed but I pointed out the classes to use (the blog post is not in sync with the code IMO, I joined it for reference only). – Pascal Thivent Feb 22 '10 at 11:29
  • Yes that is why I`m having quite a lot of trouble, I have tried modifying the code but I cant seem to find the right objects – Imran Feb 22 '10 at 11:45
  • @Imran Just use the more specialized `XmlHttpRequest` instead of `HttpRequest`. – Pascal Thivent Feb 22 '10 at 12:10
2

do it with the following code:

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

}

Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55
1

Ok I think I have solves the problem below is a working code

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


    }

}
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Imran
  • 847
  • 2
  • 9
  • 9
  • now the variable xml is giving some other information apart from the xml response, shall i simple pass this string to a parser or do I need to take care of that ..the xml response is as below ------------ DONE HTTP 200: OK Content-Type: text/xml Server: Apache-Coyote/1.1 Date: Mon, 22 Feb 2010 12:35:42 GMT Content-Encoding: gzip Transfer-Encoding: chunked – Imran Feb 22 '10 at 12:39
1

This Code is to parse the XML wraps the JSON Response and display in the front end using 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": "Cruise", "photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg" }, { "id": "2", "firstName": "Maria", "lastName": "Sharapova", "photo": "https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg" }, { "id": "3", "firstName": "James", "lastName": "Bond", "photo": "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);

`

Suneel
  • 39
  • 5
1

I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at 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 ());
}
badMonkey
  • 1,687
  • 1
  • 22
  • 23