Reputation: 1716
I am trying to get a response from a http get request on android, without using the map activity, only sending a url request to get a response to a string.
The url to get the response from: https://maps.googleapis.com/maps/api/distancematrix/json?origins=ashdod&destinations=yavne&key
and the code I am trying is:
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();
}
}
the problem is that it is throwing an exception when it reaches the connect.
P.S. This is my first time with android so please be kind with me.
Upvotes: 0
Views: 661
Reputation: 151
When doing GET request, you do not need to do output.
Just remove this line:
urlConnection.setDoOutput(true);
or you can simply change urlConnection.setDoOutput(true)
to urlConnection.setDoOutput(false)
Apart from this, you should also change this part of code to prevent garbled code:
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));
Upvotes: 3