使用 Retrofit 调用 Zomato API

huangapple go评论72阅读模式
英文:

Using Zomato Api with Retrofit

问题

我正在尝试使用 Retrofit 从 Zomato API 检索餐厅列表,但我只得到空响应,而且我找不到我做错了什么。我已经尝试过将 @Header 更改为 @Query,并将响应类型从 ApiResponse 更改为 List<Restaurant>,但问题仍然存在。

以下是调用 ZomatoApi 的 /search 端点的响应示例:

"results_found": 4072,
"results_start": 0,
"results_shown": 1,
"restaurants": [
  {
    "restaurant": {
      "R": {
        "has_menu_status": {
          "delivery": -1,
          "takeaway": -1
        },
        "res_id": 17836294,
        "is_grocery_store": false
      },
      "apikey": "75be9f9e2239fe637bf9cb1b46979d91",
      "id": "17836294",
      "name": "Cervejaria Meia Banana",
      "url": "https://www.zomato.com/porto/cervejaria-meia-banana-coimbrões?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
      "location": {
        "address": "Avenida do Infante Dom Henrique, 178, Coimbrões, Vila Nova de Gaia",
        "locality": "Coimbrões",
        "city": "Porto",
        "city_id": 311,
        "latitude": "41.1213507499",
        "longitude": "-8.6152520031",
        "zipcode": "",
        "country_id": 164,
        "locality_verbose": "Coimbrões, Porto"
      },
      // 其他属性...
    }
  }
]

Api 接口:

public interface ZomatoApi {
    @GET("search")
    Call<ApiResponse> getNearbyRestaurants(
        @Query("lat") double lat,
        @Query("lon") double lon,
        @Query("count") int count,
        @Query("radius") double radius,
        @Header("api_key") String apiKey
    );
}

ApiResponse 类:

public class ApiResponse {
    private String results_found;
    private String results_start;
    private String results_shown;
    private List<Restaurant> restaurants;

    // 构造函数和其他方法...
}

Restaurant 类:

public class Restaurant {
    private String id;
    private String name;
    Location location;

    // 构造函数和其他方法...
}

Location 类:

public class Location {
    private String address;
    private String latitude;
    private String longitude;

    // 构造函数和其他方法...
}

你的代码片段还包括了一个用于发起 API 调用的 Fragment,在其中使用 Retrofit 调用了 Zomato API 的 /search 端点,并处理了响应。

英文:

I am trying to retrieve a list of restaurants from Zomato Api using RetroFit but I am only getting null responses and I can´t find what I did wrong.I already tried to change @Header to @Query and changing the response type from ApiResponse to List&lt;Restaurant&gt; but the problem persists.

This is an example of the response of a call to the /search endpoint of ZomatoApi

&quot;results_found&quot;: 4072,
  &quot;results_start&quot;: 0,
  &quot;results_shown&quot;: 1,
  &quot;restaurants&quot;: [
    {
      &quot;restaurant&quot;: {
        &quot;R&quot;: {
          &quot;has_menu_status&quot;: {
            &quot;delivery&quot;: -1,
            &quot;takeaway&quot;: -1
          },
          &quot;res_id&quot;: 17836294,
          &quot;is_grocery_store&quot;: false
        },
        &quot;apikey&quot;: &quot;75be9f9e2239fe637bf9cb1b46979d91&quot;,
        &quot;id&quot;: &quot;17836294&quot;,
        &quot;name&quot;: &quot;Cervejaria Meia Banana&quot;,
        &quot;url&quot;: &quot;https://www.zomato.com/porto/cervejaria-meia-banana-coimbr&#245;es?utm_source=api_basic_user&amp;utm_medium=api&amp;utm_campaign=v2.1&quot;,
        &quot;location&quot;: {
          &quot;address&quot;: &quot;Avenida do Infante Dom Henrique, 178, Coimbr&#245;es, Vila Nova de Gaia&quot;,
          &quot;locality&quot;: &quot;Coimbr&#245;es&quot;,
          &quot;city&quot;: &quot;Porto&quot;,
          &quot;city_id&quot;: 311,
          &quot;latitude&quot;: &quot;41.1213507499&quot;,
          &quot;longitude&quot;: &quot;-8.6152520031&quot;,
          &quot;zipcode&quot;: &quot;&quot;,
          &quot;country_id&quot;: 164,
          &quot;locality_verbose&quot;: &quot;Coimbr&#245;es, Porto&quot;
        },
        &quot;switch_to_order_menu&quot;: 0,
        &quot;cuisines&quot;: &quot;Portuguese, Finger Food, Petiscos&quot;,
        &quot;timings&quot;: &quot;08:00 to 24:00 (Mon, Tue, Wed, Thu, Sun), 08:00 to 02:00 (Fri-Sat)&quot;,
        &quot;average_cost_for_two&quot;: 35,
        &quot;price_range&quot;: 3,
        &quot;currency&quot;: &quot;€&quot;,
        &quot;highlights&quot;: [
          &quot;Lunch&quot;,
          &quot;Debit Card&quot;,
          &quot;Breakfast&quot;,
          &quot;Dinner&quot;,
          &quot;Indoor Seating&quot;,
          &quot;Wine&quot;,
          &quot;Fullbar&quot;,
          &quot;Beer&quot;
        ],
        &quot;offers&quot;: [],
        &quot;opentable_support&quot;: 0,
        &quot;is_zomato_book_res&quot;: 0,
        &quot;mezzo_provider&quot;: &quot;OTHER&quot;,
        &quot;is_book_form_web_view&quot;: 0,
        &quot;book_form_web_view_url&quot;: &quot;&quot;,
        &quot;book_again_url&quot;: &quot;&quot;,
        &quot;thumb&quot;: &quot;https://b.zmtcdn.com/data/res_imagery/17836294_RESTAURANT_2d9d944dfca0415414fdfeca7522c396.jpg?fit=around%7C200%3A200&amp;crop=200%3A200%3B%2A%2C%2A&quot;,
        &quot;user_rating&quot;: {
          &quot;aggregate_rating&quot;: &quot;3.4&quot;,
          &quot;rating_text&quot;: &quot;Average&quot;,
          &quot;rating_color&quot;: &quot;CDD614&quot;,
          &quot;rating_obj&quot;: {
            &quot;title&quot;: {
              &quot;text&quot;: &quot;3.4&quot;
            },
            &quot;bg_color&quot;: {
              &quot;type&quot;: &quot;lime&quot;,
              &quot;tint&quot;: &quot;500&quot;
            }
          },
          &quot;votes&quot;: 24
        },
        &quot;all_reviews_count&quot;: 10,
        &quot;photos_url&quot;: &quot;https://www.zomato.com/porto/cervejaria-meia-banana-coimbr&#245;es/photos?utm_source=api_basic_user&amp;utm_medium=api&amp;utm_campaign=v2.1#tabtop&quot;,
        &quot;photo_count&quot;: 30,
        &quot;menu_url&quot;: &quot;https://www.zomato.com/porto/cervejaria-meia-banana-coimbr&#245;es/menu?utm_source=api_basic_user&amp;utm_medium=api&amp;utm_campaign=v2.1&amp;openSwipeBox=menu&amp;showMinimal=1#tabtop&quot;,
        &quot;featured_image&quot;: &quot;https://b.zmtcdn.com/data/res_imagery/17836294_RESTAURANT_2d9d944dfca0415414fdfeca7522c396.jpg&quot;,
        &quot;has_online_delivery&quot;: 0,
        &quot;is_delivering_now&quot;: 0,
        &quot;store_type&quot;: &quot;&quot;,
        &quot;include_bogo_offers&quot;: true,
        &quot;deeplink&quot;: &quot;zomato://restaurant/17836294&quot;,
        &quot;is_table_reservation_supported&quot;: 0,
        &quot;has_table_booking&quot;: 0,
        &quot;events_url&quot;: &quot;https://www.zomato.com/porto/cervejaria-meia-banana-coimbr&#245;es/events#tabtop?utm_source=api_basic_user&amp;utm_medium=api&amp;utm_campaign=v2.1&quot;,
        &quot;phone_numbers&quot;: &quot;22 3792953&quot;,
        &quot;all_reviews&quot;: {
          &quot;reviews&quot;: [
            {
              &quot;review&quot;: []
            },
            {
              &quot;review&quot;: []
            },
            {
              &quot;review&quot;: []
            },
            {
              &quot;review&quot;: []
            },
            {
              &quot;review&quot;: []
            }
          ]
        },
        &quot;establishment&quot;: [
          &quot;Casual Dining&quot;
        ],
        &quot;establishment_types&quot;: []
      }
    }
  ]
}

Api Interface

public interface ZomatoApi {
    @GET(&quot;search&quot;)
    Call&lt;ApiResponse&gt; getNearbyRestaurants(@Query(&quot;lat&quot;) double lat, @Query(&quot;lon&quot;) double lon,
                        @Query(&quot;count&quot;) int count,@Query(&quot;radius&quot;) double radius, @Header(&quot;api_key&quot;) String apiKey);
}

ApiResponse Class

package com.cmuteam.app;

import java.util.List;

public class ApiResponse {
        private String results_found;
        private String  results_start;
        private String results_shown;
        private List&lt;Restaurant&gt; restaurants;

    public ApiResponse(String results_found, String results_start, String results_shown, List&lt;Restaurant&gt; restaurants) {
        this.results_found = results_found;
        this.results_start = results_start;
        this.results_shown = results_shown;
        this.restaurants = restaurants;
    }

    public String getResults_found() {
        return results_found;
    }

    public String getResults_start() {
        return results_start;
    }

    public String getResults_shown() {
        return results_shown;
    }

    public List&lt;Restaurant&gt; getRestaurants() {
        return restaurants;
    }
}

Restaurant Class

package com.cmuteam.app;

public class Restaurant {
    private String id;
    private String name;
    Location location;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Location getLocation() {
        return location;
    }

    public Restaurant(String id, String name, Location location) {
        this.id = id;
        this.name = name;
        this.location = location;
    }
}

Location Class

public class Location {
    private String address;
    private String latitude;
    private String longitude;

    public Location(String address, String latitude, String longitude) {
        this.address = address;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public String getAddress() {
        return address;
    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

Fragment where i make the Api call

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
        mAuth = FirebaseAuth.getInstance();
        restaurantsList= new ArrayList&lt;&gt;(50);
        getApi().getNearbyRestaurants(41.12108,-8.615718100000002,20,10000,&quot;75be9f9e2239fe637bf9cb1b46979d91&quot;)
                .enqueue(new Callback&lt;ApiResponse&gt;() {
                    @Override
                    public void onResponse(Call&lt;ApiResponse&gt; call, Response&lt;ApiResponse&gt; response) {
                        List&lt;Restaurant&gt; restaurants=response.body().getRestaurants();
                        mAdapter = new RestaurantAdapter(context, restaurantsList);
                        RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
                        mRecyclerView.addItemDecoration(itemDecoration);
                        for (int i = 0; i &lt; restaurants.size(); i++) {
                            restaurantsList.add(new Restaurant(restaurants.get(i).getId(),restaurants.get(i).getName(),restaurants.get(i).getLocation()));
                            mAdapter.notifyItemInserted(i);
                        }
                    }

                    @Override
                    public void onFailure(Call&lt;ApiResponse&gt; call, Throwable t) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage(&quot;Couldn&#180;t find any nearby restaurants&quot;);
                        AlertDialog mDialog = builder.create();
                        mDialog.show();
                    }
                });
    }

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mContentView = inflater.inflate(R.layout.poi_list, container,false);
        mRecyclerView = mContentView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContentView.getContext()));
        mRecyclerView.setAdapter(mAdapter);
        return mContentView;
    }

    private Retrofit getRetrofit(){
        return new Retrofit.Builder()
                .baseUrl(&quot;https://developers.zomato.com/api/v2.1/&quot;)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private ZomatoApi getApi(){
        return  getRetrofit().create(ZomatoApi.class);
    }

答案1

得分: 0

授权头部称为"user-key",而不是在zomato文档中提到的"api_key"。

英文:

The authorization header is called "user-key" not "api_key" as mentioned in zomato docs.

huangapple
  • 本文由 发表于 2020年8月29日 06:37:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63641680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定