【问题标题】:Android: How to get JSON object from Zomato API?Android:如何从 Zomato API 获取 JSON 对象?
【发布时间】:2016-09-11 12:48:22
【问题描述】:

我的目标是使用 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"

任何帮助将不胜感激。

【问题讨论】:

    标签: android curl zomato-api


    【解决方案1】:

    您可以使用 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}
    

    【讨论】:

      【解决方案2】:

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

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

      我得到了我需要的东西。

      【讨论】:

        猜你喜欢
        • 2016-09-16
        • 2020-04-22
        • 2013-05-03
        • 1970-01-01
        • 2016-11-16
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多