首页 文章

Android:如何从Zomato API获取JSON对象?

提问于
浏览
1

我的目标是使用Zomato API显示附近餐馆的列表 . 我首先需要JSON对象来获取这些餐馆的名称 . 我已经获得了API密钥,我知道请求URL看起来像这样

https://developers.zomato.com/api/v2.1/search?lat=LATITUDE&lon=LONGITUDE

从文档https://developers.zomato.com/documentation,似乎我必须使用一个名为Curl的东西,但我不知道Curl是什么 .

curl -X GET --header "Accept: application/json" --header "user-key: API key" "https://developers.zomato.com/api/v2.1/search?&lat=LATITUDE&lon=LONGITUDE"

任何帮助,将不胜感激 .

2 回答

  • 2

    您可以使用Rest Client通过标头和URL调用请求 . 我建议使用VolleyRetrofit来做 . 以下是使用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);
    

    我得到的回应是:

    {"restaurants":[],"results_found":0,"results_shown":0,"results_start":0}
    
  • 1

    我注意到Curl包含 --header 所以我对URL中的 Headers 进行了一些研究,并在 url.openConnection(); 之后添加了这两行

    URLConnection urlConnection = url.openConnection();
    urlConnection.setRequestProperty("Accept", " application/json");
    urlConnection.setRequestProperty("user-key", " "+API_KEY);
    

    我得到了我需要的东西 .

相关问题