0

我正在 android studio 中制作卡路里计数器应用程序。我已经创建了所有适配器和布局,但我在一个地方感到震惊,我正在尝试使用快速 API 食品卡路里数据搜索 API,它提供了一个 URL 和一个我不知道在哪里添加该密钥的密钥。

 private void parseJSON() {
 String url="edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data?key=ingr=1%20large%20apple";
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {
                JSONArray jsonArray = null;
                try {
                    jsonArray = response.getJSONArray("hits");

                    for (int i = 0; i < jsonArray.length(); i++)
                    {
                        JSONObject hit = jsonArray.getJSONObject(i);
                        String name = hit.getString("name");
                        int protein = hit.getInt("protein");
                        int carbs = hit.getInt("carbs");
                        int fats = hit.getInt("fats");
                        int calories = hit.getInt("calories");

                        mExampleList.add(new element_item(name,protein,carbs,fats,calories));
                    }

                    mExampleAdapter = new elementAdaptor(MainActivity.this, mExampleList);
                    mRecyclerView.setAdapter(mExampleAdapter);

                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }
4

1 回答 1

0

您应该在错误侦听器之后添加相应的标头

        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {....}, new Response.ErrorListener() {....}) {

    @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String>  params = new HashMap<>();
            params.put("X-RapidAPI-Host", "Your api Host");
            params.put("X-RapidAPI-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");   //changedkey
            return params;
       }};
于 2021-05-22T05:22:20.657 回答