在Java中如何从/places/v1/autosuggest获取JSON响应?
我在使用Here API时遇到了一些问题。当我运行curl命令时,我会得到一个JSON对象,但当我在代码中尝试它时,我会不断得到HTML。有人能帮我吗?我做错了什么? 这是curl命令:在Java中如何从/places/v1/autosuggest获取JSON响应?,java,curl,here-api,Java,Curl,Here Api,我在使用Here API时遇到了一些问题。当我运行curl命令时,我会得到一个JSON对象,但当我在代码中尝试它时,我会不断得到HTML。有人能帮我吗?我做错了什么? 这是curl命令: curl \ --compressed \ -H 'Accept-Encoding:gzip' \ -H 'Accept-Language:en-US,en;q=0.5' \ --get 'https://places.cit.api.here.com/places/v1/autosugges
curl \
--compressed \
-H 'Accept-Encoding:gzip' \
-H 'Accept-Language:en-US,en;q=0.5' \
--get 'https://places.cit.api.here.com/places/v1/autosuggest' \
--data-urlencode 'app_code=my_code' \
--data-urlencode 'app_id=my_id' \
--data-urlencode 'at=48.13642,11.57755' \
--data-urlencode 'pretty=true' \
--data-urlencode 'q=Hofbräuhaus am Platz'
这是我的Java代码:
private void searchForPlacesInMunich(String place) throws IOException {
String link = "https://places.cit.api.here.com/places/v1/autosuggest"
+ "?app_id=" + app_id
+ "&app_code=" + app_code
+ "&at=" + latitude + "%2C" + longitude
+ "&q=" + place
+ "&pretty";
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestMethod("GET");
con.connect();
System.out.println("Length : " + con.getContentLength());
Reader reader = null;
if ("gzip".equals(con.getContentEncoding())) {
reader = new InputStreamReader(new GZIPInputStream(con.getInputStream()));
}
else {
reader = new InputStreamReader(con.getInputStream());
}
while (true) {
int ch = reader.read();
if (ch==-1) {
break;
}
System.out.print((char)ch);
}
}
尝试使用JSONObject
JSONObject myObject = new JSONObject(result);
来源:刚刚找到了一种获取JSON而不是UI的方法:答案非常简单。只需在URL中添加回调
受到的启发,我不确定它是否会起作用,因为我得到了一个HTML响应(HTML标签和所有东西)。我可能问错了问题。这里的API比Java更重要。我的意思是,当我在浏览器中访问URL时,我会得到一个普通的站点,在左下角有一个curl命令,可以复制并获得JSON格式的响应(原始,没有任何HTML)这就是我试图在Java代码中获得的更多信息,因为我觉得我没有很好地解释这个问题:问题是:当我通过internet浏览器发送get请求时,它工作正常(因为它得到HTML作为响应),但是在页面左下角的“Take this request home”下有一个curl命令(问题是curl命令)。当我在终端中运行该命令时,我会得到原始的JSON响应(没有HTML),但当我运行Java代码时(也在问题中),我只会得到HTML响应,而不是预期的JSON。