改进获取方法参数

时间:2018-11-27 20:08:01

标签: android get retrofit

 public class RetrofitClient {

public static String BASE_URL = "https://android-full-time-task.firebaseio.com";
private static Retrofit retrofit;
public static Retrofit getRetrofit(){
    if(retrofit==null){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}

public interface ApiInterfaceService {
@GET("/data.json")
Call<List<FoodItem>> getFoodItems();}

public class RetrofitApi {

public static void getFoodItemsList(final ApiListener<List<FoodItem>> listener) {
    ApiInterfaceService service = RetrofitClient.getRetrofit().create(ApiInterfaceService.class);
    Call<List<FoodItem>> callFood = service.getFoodItems();
    callFood.enqueue(new Callback<List<FoodItem>>() {
        @Override
        public void onResponse(Call<List<FoodItem>> call, final Response<List<FoodItem>> response) {
            if(response!=null) {
                List<FoodItem> foodItems = response.body();
                listener.onSuccess(foodItems);
            }
        }

        @Override
        public void onFailure(Call<List<FoodItem>> call, Throwable t) {
            Log.d("Retrofit Failure",t.getLocalizedMessage());
        }
    });
}

}

这里如何使用@GET方法?如何映射这个网址 https://android-full-time-task.firebaseio.com/data.json 我是Retrofit的新手,不知道如何使用get方法。

1 个答案:

答案 0 :(得分:0)

@GET是一个HTTP注释,用于指定请求类型和相对 URL。返回值将响应包装在类型为 Call 的对象中。预期的结果。

您问题中的代码是一个完整的示例:

Call<List<FoodItem>> callFood = service.getFoodItems();
//this line calls getFoodItems method defined in interface via @GET annoation, 
//which will send a get request using baseUrl + relative url,

callFood.enqueue(new Callback<List<FoodItem>>() {
    @Override
    public void onResponse(Call<List<FoodItem>> call, final Response<List<FoodItem>> response) {
        if(response!=null) {//the response result will be wrapped in a Call object
            List<FoodItem> foodItems = response.body();
            listener.onSuccess(foodItems);
        }
    }

    @Override
    public void onFailure(Call<List<FoodItem>> call, Throwable t) {
        Log.d("Retrofit Failure",t.getLocalizedMessage());
    }
});