【问题标题】:The given code is returning me an empty JSON output给定的代码返回一个空的 JSON 输出
【发布时间】:2016-10-09 12:45:03
【问题描述】:
void url_get(double lati,double longi) {
            URL url = null;
            try {
                url = new URL("https://maps.googleapis.com/maps/api/place/search/json?&location="+lati+","+longi+"&radius=1000&types=hospital&sensor=true&key=MY_KEY);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) url.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                TextView json = (TextView) findViewById(R.id.json3);
                String theString = IOUtils.toString(in, "UTF-8");
                json.setText(theString);
                //System.out.println(in);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }

        }

当我硬编码纬度和经度值时,代码运行良好。但是,当我尝试通过函数传递纬度和经度值时,它无法被识别。我想 URL 没有正确构建。请问建议一种使用纬度和经度值构建我的网址的方法?

【问题讨论】:

  • 你把 lat 和 long 硬编码成什么?可以提供样品吗?

标签: java android json api url


【解决方案1】:

您应该使用以下方法将值转换为字符串:

Double.toString(double);

或:

String.valueOf(double);

所以你的字符串应该是这样的:

url = new URL("https://maps.googleapis.com/maps/api/place/search/json?&location="+String.valueOf(lati)+","+String.valueOf(longi)+"&radius=1000&types=hospital&sensor=true&key=MY_KEY");

注意

在您的代码中,字符串末尾缺少"

【讨论】:

  • 愚蠢的我!非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
相关资源
最近更新 更多