0

there are some some web site that call end point and recive a json response. I would like to know how in myAndroid app i can call the web site and retrive the json data that he show. Example: this is a drivenow site map

drivenow map link

if i open debug mode of browser i see this ajax call that give a josn response. I would like to know i can call this website and take (grap) this response in my android app so i can use the json Any idea? Help? Thanks

APPGIS
  • 353
  • 1
  • 10
  • 20
  • You should be able to get the URL of the web service using your browser developer tools. (you probably need authorization from the website to use their web service) – Sébastien Feb 22 '17 at 09:35

1 Answers1

0

You can perform GET/POST request using two ways.

Some 3rd party network request libraries

I would suggest using robospice. Using robospice you perform a network request and give it a POJO. For more info on POJO refer to the link below

https://github.com/stephanenicolas/robospice/wiki/Starter-Guide

What is RoboSpice Library in android

Using native Android/Java code

Use this function to get JSON from URL.

public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {

HttpURLConnection urlConnection = null;

URL url = new URL(urlString);

urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);

urlConnection.setDoOutput(true);

urlConnection.connect();

BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));

char[] buffer = new char[1024];

String jsonString = new String();

StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
    sb.append(line+"\n");
}
br.close();

jsonString = sb.toString();

System.out.println("JSON: " + jsonString);

return new JSONObject(jsonString);}

Then use it like this:

try{
  JSONObject jsonObject = getJSONObjectFromURL(String urlString);

  // Parse your json here

} catch (IOException e) {
  e.printStackTrace();
} catch (JSONException e) {
  e.printStackTrace();
}

Do not forget to add Internet permission in your manifest

<uses-permission android:name="android.permission.INTERNET" />

For more info on parsing JSON visit How to parse JSON in Android

Note

You don't have to manually parse your json if you use a 3rd party library.

Community
  • 1
  • 1