我试图从android上的http get请求获得响应,而不使用map活动,只发送一个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();
}
}
问题是它到达连接时会抛出异常。
P.S。这是我第一次使用android,所以请和我好心。
答案 0 :(得分:3)
执行GET请求时,您不需要输出。
只需删除此行:
urlConnection.setDoOutput(true);
或者您只需将urlConnection.setDoOutput(true)
更改为urlConnection.setDoOutput(false)
除此之外,您还应该更改此部分代码以防止出现乱码:
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));