0

I want to get the current time from this webpage: http://api.geonames.org/timezone?lat=47.01&lng=10.2&username=demo At first I need to get the info from that page using HTTP, then parsing XML and show the current time in the console.

My expected message from webservice is current time.

I was trying smth like this but it doesn't work. I have such an output: [#document: null]

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStream;

import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

 import org.xml.sax.SAXException;

 public class Main {

public static void main(String[] args) throws IOException, ParserConfigurationException {

    String uri =
            "http://api.geonames.org/timezone?lat=47.01&lng=10.2&username=demo";

        URL url = new URL(uri);
        HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");

        InputStream xml = connection.getInputStream();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        try {
            Document doc = (Document) db.parse(xml);
            System.out.println(doc);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
}
Viola
  • 487
  • 1
  • 10
  • 33

1 Answers1

1

Look at your import :

import javax.swing.text.Document;

The cast can only fail.
The cast is not required as DocumentBuilder.parse() returns a org.w3c.dom.Document object.

Instead import this class :

import org.w3c.dom.Document;

Then you could use XPath to retrieve the value of the time element:

Document doc =  db.parse(xml);
XPath xPath = XPathFactory.newInstance().newXPath();
String time = (String)xPath.evaluate("/geonames/timezone/time",
            doc.getDocumentElement(), XPathConstants.STRING);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • thank's, I've changed this, but now I have such an input: [#document: null] – Viola Jan 21 '18 at 21:20
  • @Viola: take a look at this: https://stackoverflow.com/questions/2018868/documentbuilder-parseinputstream-returns-null – Andrey Tyukin Jan 21 '18 at 21:25
  • I think that the request doesn't return the expected result. Try to run it from the browser to check it. I will edit my answer to explain how retrieve the information with XPath. – davidxxx Jan 21 '18 at 21:28
  • Ah. I have just tested. I have an error message now : "the daily limit of 30000 credits for demo has been exceeded. Please use an application specific account. Do not use the demo account for your application". – davidxxx Jan 21 '18 at 21:37
  • thank's, it works, but only when demo version is available – Viola Jan 21 '18 at 22:08