Android: How to get JSON object from Zomato API?
My goal is to display a list of nearby restaurants using the Zomato API. I first need the JSON object to get the names of these restaurants. I've already got the API key and I know that the request URL would look like this
https://developers.zomato.com/api/v2.1/search?lat=LATITUDE&lon=LONGITUDE
From the documentation https://developers.zomato.com/documentation, it seems that I have to use something called Curl but I don't know what Curl is.
curl -X GET --header "Accept: application/json" --header "user-key: API key" "https://developers.zomato.com/api/v2.1/search?&lat=LATITUDE&lon=LONGITUDE"
Any help would be appreciated.
Solution 1:
You can use a Rest Client to call the request with the header and URL. I suggest using Volley or Retrofit to do it. Here is an example using Volley:
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://developers.zomato.com/api/v2.1/search?&lat=27&lon=153";
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR", "error => " + error.toString());
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user-key", "55a1d18014dd0c0dac534c02598a3368");
params.put("Accept", "application/json");
return params;
}
};
queue.add(postRequest);
And the response I've got:
{"restaurants":[],"results_found":0,"results_shown":0,"results_start":0}
Solution 2:
I noticed that the Curl contained --header
so I did some research about headers in URLs and added these 2 lines after url.openConnection();
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Accept", " application/json");
urlConnection.setRequestProperty("user-key", " "+API_KEY);
And I got what I needed.