0
我想從android的http獲取請求獲取響應,而不使用地圖活動,只發送url請求以獲取對字符串的響應。Http GET在android中的請求錯誤
的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.這是我第一次與機器人,所以請與我友善。
您可以添加異常堆棧跟蹤 – bmavus
和異常類 – maslan