我正在尝试从 Android 上的 http get 请求获取响应,而不使用 map Activity ,仅发送 url 请求来获取对字符串的响应。
获取响应的 URL: https://maps.googleapis.com/maps/api/distancematrix/json?origins=ashdod&destinations=yavne&key
我正在尝试的代码是:
HttpURLConnection urlConnection= null;
URL url = null;
String response = "";
try {
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = null;
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp = "";
while((temp = bReader.readLine()) != null){
//Parse data
response += temp;
}
bReader.close();
inStream.close();
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject Jresponse = new JSONObject(response.toString());
JSONArray rows = Jresponse.getJSONArray("rows");
JSONObject rows_obj = (JSONObject) rows.get(0);
JSONArray elems = rows_obj.getJSONArray("elements");
JSONObject elems_obj = (JSONObject) elems.get(0);
JSONObject dist = (JSONObject) elems_obj.get("distance");
JSONObject dur = (JSONObject) elems_obj.get("duration");
finalDistance = dist.getInt("value");
finalDuration = dist.getInt("value");
} catch (JSONException e) {
e.printStackTrace();
}
}
问题是它在到达连接时抛出异常。
附注这是我第一次使用 Android,所以请善待我。
最佳答案
在进行GET请求时,不需要进行输出。
只需删除此行:
urlConnection.setDoOutput(true);
或者您可以简单地将 urlConnection.setDoOutput(true)
更改为 urlConnection.setDoOutput(false)
除此之外,还应该修改这部分代码,防止出现乱码:
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));
关于java - android中的Http GET请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35830898/