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/