2011-04-20 139 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