Google Directions API accessed via Java
I'm trying to create a simple java application. It want to be able to input the origin and destination and to output the path it takes in xml.
This is what i've got so far. My main focus is to get a xml output to the console.
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class directionService{
public static void main(String[] args) {
String start = "geelong";
String finish = "melbourne";
String region = "au";
System.out.println(calculateRoute(start,finish,region));
}
private static String calculateRoute(String start, String finish, String region){
String result = "";
String urlString = "http://maps.googleapis.com/maps/api/directions/json?sensor=false&origin="+start+"&destination="+finish;
System.out.println(urlString);
try{
URL urlGoogleDirService = new URL(urlString);
HttpURLConnection urlGoogleDirCon = (HttpURLConnection)urlGoogleDirService.openConnection();
urlGoogleDirCon.setAllowUserInteraction( false );
urlGoogleDirCon.setDoInput( true );
urlGoogleDirCon.setDoOutput( false );
urlGoogleDirCon.setUseCaches( true );
urlGoogleDirCon.setRequestMethod("GET");
urlGoogleDirCon.connect();
DocumentBuilderFactory factoryDir = DocumentBuilderFactory.newInstance();
DocumentBuilder parserDirInfo = factoryDir.newDocumentBuilder();
Document docDir = parserDirInfo.parse(urlGoogleDirCon.getInputStream());
urlGoogleDirCon.disconnect();
result = docDir.toString();
return result;
}
catch(Exception e)
{
System.out.println(e);
return null;
}
};
}
It throws this error
java.net.ConnectException: Connection timed out: connect
I've tried getting data from other webservices and it returns an xml dump fine. I read about having a key in the google documentation, is this required? It seems to work fine if I 开发者_Go百科directly input the query into my browser.
http://maps.googleapis.com/maps/api/directions/xml?sensor=false&origin=geelong&destination=melbourne
Any help would be greatly appriciated!
Thanks, Steve
Are you behind a firewall? You may need to enter your proxy server details before your call:
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost", proxy);
systemProperties.setProperty("http.proxyPort", port);
System.setProperty("http.proxyUser", user);
System.setProperty("http.proxyPassword", password);
I think you need to setConnectionTimeout on HttpURLConnection. Try also this link in stackoverflow.
精彩评论