繁体   English   中英

如何从Java中的/ places / v1 / autosuggest获取JSON响应?

[英]How do I get the JSON response from /places/v1/autosuggest in Java?

我在使用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/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);
          }
    }

刚刚找到了一种获取JSON而不是UI的方法:答案非常简单。 只需在受此启发的URL中添加回调,即可将REST api返回json上的Web ui

尝试使用JSONObject

JSONObject myObject = new JSONObject(result);

来源: 从HTTP响应获取JSON对象

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM