我已经编写了以下代码,以从Java程序(故意遗漏了APPKEY)访问Open MapQuest API:
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: []
从例如发出完全相同的查询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}]
当我通过
MapQuest
询问时,为什么Java
不返回这些数据?是否有一些我不知道的转义字符?我需要设置一些特殊的用户代理吗?我是否以错误的方式查询连接对象?毕竟,该服务返回OK(HTTP状态代码200),因此对于我的请求似乎还不错。为什么不回答?
最佳答案
大多数情况下,这些问题与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);