2012-09-23 64 views
0

我使用谷歌地理編碼API來獲得結果,但它返回「ZERO_RESULTS」。以下是代碼谷歌GeoCoding返回ZERO_RESULTS

public class GeoCode { 

public static void main(String[] args) throws Exception { 
    GeoCode.geocode("latlng=40.714224,-73.961452"); 
    } 
private static final String URL = "http://maps.googleapis.com/maps/api/geocode/json"; 


public static void geocode(String address) throws Exception { 

    URL url = new URL(URL + "?" + URLEncoder.encode(address, "UTF-8") + "&sensor=false"); 
    URLConnection conn = url.openConnection(); 
    ByteArrayOutputStream output = new ByteArrayOutputStream(1024); 
    IOUtils.copy(conn.getInputStream(), output); 
    output.close(); 

    //JSONObject json = new JSONObject(output.toString()); 
    System.out.println(output.toString()); 
} 
} 

當我在瀏覽器的地址欄上手動使用地址時,它向我展示了瀏覽器上的json結果。但是上面的代碼實際上是錯誤的,它在json中返回「ZERO_RESULTS」?

回答

2

您不需要編碼與URLEncoder的地址,只是做:

URL url = new URL(URL + "?" + address + "&sensor=false"); 
URLConnection conn = url.openConnection(); 
ByteArrayOutputStream output = new ByteArrayOutputStream(1024); 
IOUtils.copy(conn.getInputStream(), output); 
output.close(); 
System.out.println(output.toString()); 

或可能更好:

URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?" + address + "&sensor=false"); 
try { 
    output = new Scanner(url.openStream()).useDelimiter("\\A").next()); 
} catch (java.util.NoSuchElementException e) { 
    //empty result 
}