java - 给定的代码返回一个空的 JSON 输出

标签 java android json api url

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 构建不正确。您能否建议一种使用纬度和经度值构建我的 url 的方法?

最佳答案

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

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");

注意

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

关于java - 给定的代码返回一个空的 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39943781/

相关文章:

java - 字符串操作 - 还有其他有效的方法吗?

android - 如何在 Android 中播放直播视频

java - 如何将 JSONArray 转换为通用 List<T>?

java - 高枕无忧,无法验证 JSON 数组响应

java - 删除大于 1000 的 ID 时出现问题

java - 将 Java 交叉编译为 JavaScript

安卓错误: "Not a Statement" in a specific block of code

android - android 支持包修订版 12 中的操作栏支持

javascript - 循环范围 : 1 to 1000 的 Json mustache

java - 比较 Java 中的对象