2016-03-02 61 views
0

我寫了這個代碼從Java程序訪問打開MapQuest的API(APPKEY冷落故意..):查詢開放API的MapQuest沒有給出結果

public class OpenMapQuestAPITest { 

    private final static String APPKEY="..."; 

    public static void main(String[] args) throws Exception { 
    String address="Germany, Hannover, Am Hohen Ufer 3A"; 
    URL url=new URL("http://open.mapquestapi.com/nominatim/v1/search.php?key="+ 
     APPKEY+"&format=json&q="+address.replace(' ','+')); 
    System.out.println("Query: "+url.toString()); 
    HttpURLConnection con=(HttpURLConnection)url.openConnection(); 
    int responseCode = con.getResponseCode(); 
    System.out.println("Response Code : " + responseCode); 
    StringBuffer response = new StringBuffer(); 
    try (BufferedReader in= 
     new BufferedReader(new InputStreamReader(con.getInputStream()))) { 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
     response.append(inputLine); 
    } 
    System.out.println("Response: "+response.toString()); 
    } 

} 

我得到這個(左鍵故意添加換行符):

Query: http://open.mapquestapi.com/nominatim/v1/search.php?↵ 
     key=...&format=json&q=Germany,+Hannover,+Am+Hohen+Ufer+3A 
Response Code : 200 
Response: [] 

從eg發出完全相同的查詢Chrome瀏覽器提供了正確的迴應:

[{"place_id":"1528890","licence":"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright", 
    "osm_type":"node","osm_id":"322834134", 
    "boundingbox":["52.3729826","52.3729826","9.7304606","9.7304606"], 
    "lat":"52.3729826","lon":"9.7304606", 
    "display_name":"3a, Am Hohen Ufer, Mitte, Hannover, Region Hannover, Niedersachsen, 30159, Deutschland", 
    "class":"place","type":"house","importance":0.511}] 

,當我通過Java問爲什麼MapQuest不會返回這些數據?有沒有我不知道的角色逃脫?我是否需要設置一些特殊的用戶代理?我是否以錯誤的方式查詢連接對象?畢竟,服務返回OK(HTTP狀態代碼200),所以對我的請求似乎感覺不錯。

它爲什麼不回答?

回答

1

大多數情況下,這些問題都與網址編碼有關。

1.先嚐試網址編碼。

String address="Germany, Hannover, Am Hohen Ufer 3A"; 
URL url=new URL("http://open.mapquestapi.com/nominatim/v1/search.php?key="+ 
    APPKEY+"&format=json&q="+address.replace(' ','+')); 

嘗試:

URLEncoder.encode(address.replace(' ','+'), "UTF-8")); 

2.你可以去org.apache.commons.httpclient.HttpClient API。它有一個類PostMethod(org.apache.commons.httpclient.methods.PostMethod),您可以使用它添加參數。 (而不是HttpUrlConnection) Like

HttpClient hc = new HttpClient(); 
PostMethod pm = new PostMethod(url); 
// add parameters to it. 
pm.addParameter("format","json"); 
hc.executeMethod(pm);