2011-04-20 90 views
0

我正在尝试创建一个简单的Java应用程序。它希望能够输入源和目的地并输出它在xml中所需的路径。通过Java访问的Google路线API

这就是我到目前为止。我主要关注的是获得一个xml输出到控制台。

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

    }; 

} 

它抛出这个错误

java.net.ConnectException:连接超时:连接

我试着从其他Web服务获取数据并返回一个XML导出罚款。我阅读了关于在谷歌文档中有一个关键,这是必需的?它似乎工作正常,如果我直接输入查询到我的浏览器。

http://maps.googleapis.com/maps/api/directions/xml?sensor=false&origin=geelong&destination=melbourne

任何帮助将大大appriciated!

谢谢你,史蒂夫

回答

0

你在防火墙后面吗?您可能需要在拨打电话之前输入您的代理服务器的详细信息:

Properties systemProperties = System.getProperties(); 
systemProperties.setProperty("http.proxyHost", proxy); 
systemProperties.setProperty("http.proxyPort", port); 
System.setProperty("http.proxyUser", user); 
System.setProperty("http.proxyPassword", password); 
0

我认为你需要setConnectionTimeout上HttpURLConnection类。 请尝试这个link在计算器中。

+0

我刚刚给了一个去,没有。我尝试了值为0,15000和150000. java.net.ConnectException:连接超时:连接。 – Steveo 2011-04-20 06:37:26

+0

我也试过改变HttpURLConnection.setFollowRedirects(false);但没有变化。 – Steveo 2011-04-20 06:38:46