【问题标题】:how to make generic retrofit library for api calling如何为 api 调用制作通用改造库
【发布时间】:2020-08-29 11:27:25
【问题描述】:

我正在研究 API 集成。我想为 API 集成创建通用类。它可以适应所有 API 集成。现在我对所有 API 使用单独的代码。我是android应用程序开发的新手。所以请指导我。

 public void getHomeCategoryDetailApi(Context context) {
    final ProgressDialog loadingDialog = ProgressDialog.show(context, "Please wait", "Loading...");
    Retrofit restAdapter = ApiLists.retrofit;
    ApiLists apiCall = restAdapter.create(ApiLists.class);
    Call<HomeCategoryModelClass> call = apiCall.homePageCatListAPI();
    Log.d(TAG, "CategoryDetail : " + call.request()+" \n"+apiCall.homePageCatListAPI().toString());

    call.enqueue(new Callback<HomeCategoryModelClass>() {
        @Override
        public void onResponse(Call<HomeCategoryModelClass> call, Response<HomeCategoryModelClass> response) {
            Log.d(TAG, "onResponse: CategoryDetail:" + response.body());
            Log.d(TAG, "onResponse:  response.code():" + response.code());
            if (response.body() == null) {
                loadingDialog.dismiss();
                globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
            } else {
                loadingDialog.dismiss();
                if (response.body().getStatusCode().equalsIgnoreCase("1")) {
                    homeCategoryImageMenu = (ArrayList<Menu>) response.body().getMenu();
                    thirdHorizontalRecyclerAdapter.notifyDataSetChanged();
                } else {
                    globalClass.showAlertDialog(getActivity(), "Alert", "" + response.body().getStatus(), false);
                }
            }
            if (response.errorBody() != null) {
                try {
                    Log.d(TAG, "onResponse: response.errorBody()===>" + response.errorBody().string());
                    if (loadingDialog.isShowing() && loadingDialog != null) {
                        loadingDialog.dismiss();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Call<HomeCategoryModelClass> result, Throwable t) {
            Log.d(TAG, "onFailure: " + result.toString());
            loadingDialog.dismiss();
            globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
        }
    });

}

【问题讨论】:

  • 创建公用事业网络类并使用Interface 进行回调。
  • 我想做这样的。我只是传递一些需要参数

标签: android retrofit


【解决方案1】:

这是调用 API 的基本方式

public class APIResponse {
private static String TAG = APIResponse.class.getSimpleName();

public static <T> void callRetrofit(Call<T> call, final String strApiName, Context context, final ApiListener apiListener) {
    final ProgressDialog progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading...");
    progressDialog.setCancelable(false);
    progressDialog.show();

    call.enqueue(new Callback<T>() {
        @Override
        public void onResponse(Call<T> call, Response<T> response) {
            if (strApiName.equalsIgnoreCase("LoginApi")) {

                if (response.isSuccessful()) {
                    Log.d(TAG, "onResponse: " + response.body().toString());
                    //  NearByNurse nearByNurse = (NearByNurse) response.body(); // use the user object for the other fields
                    // apiListener.success(url,nearByNurse);
                    progressDialog.dismiss();
                } else {
                    try {
                        Log.d(TAG, "onResponse: " + response.errorBody().string());
                        apiListener.error(strApiName, response.errorBody().string());
                        progressDialog.dismiss();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else if (strApiName.equalsIgnoreCase("")) {
                //Patient user = (Patient) response.body();
            }
        }

        @Override
        public void onFailure(Call<T> call, Throwable t) {
            Log.d(TAG, "onFailure: " + t.toString());
            if (strApiName.equalsIgnoreCase("searchNearbyTest")) {
                apiListener.failure(strApiName, t.toString());
            }
            progressDialog.dismiss();
        }
    });
}

在 API 调用端

private void loginApi() {
    Retrofit retrofit = ApiLists.retrofit;
    ApiLists apiList = retrofit.create(ApiLists.class);
    Call<JsonElement> loginApiCall = apiList.loginApi("kjdf", "fkldngdkl", "lkfdxngl", "kjngn", "jksdgkj");
    APIResponse.callRetrofit(loginApiCall, "LoginApi", LoginActivity.this, this);
}
@Override
public void success(String strApiName, Object response) {
    if (strApiName.equals("LoginApi")) {
    }
}

@Override
public void error(String strApiName, String error) {
    if (strApiName.equals("LoginApi")) {

    }
}

@Override
public void failure(String strApiName, String message) {
    if (strApiName.equals("LoginApi")) {

    }

对 API 响应的接口调用。

public interface ApiListener {
void success(String strApiName, Object response);
void error(String strApiName, String error);
void failure(String strApiName, String message);
 }

【讨论】:

  • 什么是 ApiLists?
  • API列表为接口,所有api调用都在其中提及。
【解决方案2】:

这是我常用的函数基本调用Api.java

public class Api {
private void basicCall(Call<DataResponse> call) {
    if (call == null) {
        listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
        return;
    }
    call.enqueue(new Callback<DataResponse>() {
        @Override
        public void onResponse(@NonNull Call<DataResponse> call, @NonNull Response<DataResponse> response) {
            int code = response.code();
            //Check http ok
            if (code == HttpURLConnection.HTTP_OK) {
                //Check status
                if (response.body().getStatus() == Config.STATUS_OK) {
                    //Everything's OK
                    listener.onResponseCompleted(Config.STATUS_OK, response.body().getError(), response.body().getData());
                } else {
                    listener.onResponseCompleted(Config.STATUS_FAILED, response.body().getError(), null);
                }
            } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
                try {
                    ErrorResponse error = Api.gson.fromJson(response.errorBody().string(), ErrorResponse.class);
                    listener.onResponseCompleted(Config.STATUS_401, error.getError(), error.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
            }
        }

        @Override
        public void onFailure(@NonNull Call<DataResponse> call, @NonNull Throwable t) {
            listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
        }
    });
}
//And you can use
public void getProductList(OnResponseCompleted listener) {
    this.listener = listener;
    Call<DataResponse> call = apiService.getProductList();
    basicCall(call);
}
}
//or orther function

这是 ApiService.java

public interface ApiInterface {
 @POST("product/list")
 Call<DataResponse> getProductList();
}

这是 OnResponseCompleted.java

public interface OnResponseCompleted {
void onResponseCompleted(int status, String error, Object data);
}

【讨论】:

  • 这里的数据响应是什么,我在每个 api 中使用不同的模型类,所以我该如何管理它
【解决方案3】:

我想做这样的。我只是传递一些需要参数....

public void showAlertDialog(Context context, String title, String message,
                            Boolean status) {

    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

   alertDialog.setTitle(title);

    // Set Dialog Message
    alertDialog.setMessage(message);
    alertDialog.setCancelable(false);
    if (status != null)
        // Set alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.ic_success : R.drawable.ic_fail);

    // Set OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    // Show Alert Message
    alertDialog.show();
}

【讨论】:

  • 是的,我们明白了。现在删除它。
  • 天啊,很好的答案:D
【解决方案4】:

试试这个代码.. 在这段代码中,Retrofit 对象设置在一个类中,所有 api 调用到接口中。

public class ApiClient {
private final static String BASE_URL = "https://api.github.com";

public static ApiClient apiClient;
private Retrofit retrofit = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}
}

之后调用api进入api接口..

public interface ApiInterface {
@GET("{affenpinscher}/images")
Call<Product> getProductData(@Path("affenpinscher") String breed);
@GET("getProductDetailByProductId?ProductId=3")
Call<JsonObject> ITEM_DESCRIPTION_RESPONSE_CALL();

@POST("linke")
Call<Response> passJsonData(@Body JsonData jsonData);

@GET("/users/waadalkatheri/repos")
Call<Response> getdata();
}

当您在代码下方使用的活动或片段中调用 api 时..

ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
    Call<ResponseData> responseCall = apiInterface.getdata();
    responseCall.enqueue(new Callback<ResponseData>() {
        @Override
        public void onResponse(Call<ResponseData> call, retrofit2.Response<ResponseData> response) {
            if (response.isSuccessful() && response.body() != null && response != null) {
                Toast.makeText(getApplicationContext(), "GetData" + response.body().getLanguage(), Toast.LENGTH_SHORT).show();


            }
        }

        @Override
        public void onFailure(Call<ResponseData> call, Throwable t) {
            Log.d("Errror", t.getMessage());
        }
    });

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 2021-12-15
    • 2018-05-26
    • 2021-05-24
    • 2018-02-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多