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