我编写了这段代码来从 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: []
从例如发出完全相同的查询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),所以看起来对我的请求感觉还不错。
为什么不回复?
最佳答案
大多数时候这些问题与 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);
关于java - 使用 Java HttpURLConnection 查询 Open MapQuest API 没有给出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742177/