Hi . 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.
Get your response via a regular http-request, using:
- Apache HttpComponents
- the built-in
URLConnection con = new URL("http://example.com").openConnection()
;
The next step is parsing it. Take a look at this article for a choice of parser.
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.
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();
}
}
}
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
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 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));