【问题标题】:Query Open MapQuest API with Java HttpURLConnection gives no result使用 Java HttpURLConnection 查询 Open MapQuest API 没有结果
【发布时间】:2016-03-02 08:42:11
【问题描述】:

我已经编写了这段代码来从 Java 程序访问 Open MapQuest API(APPKEY 故意遗漏了..):

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: []

从 e.g. 发出完全相同的查询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),看来我的请求感觉还不错。

为什么不回答?

【问题讨论】:

    标签: java json httpurlconnection mapquest


    【解决方案1】:

    这些问题大多与 url 编码有关。

    1.先试试 url 编码。

    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) 喜欢

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

    【讨论】:

      猜你喜欢
      • 2018-07-14
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多