如何为api调用制作通用改造库

时间:2018-02-22 07:33:26

标签: android retrofit

我正致力于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);
        }
    });

}

4 个答案:

答案 0 :(得分:1)

这是我的常用功能基本调用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);
}

答案 1 :(得分:0)

我想这样做。我只是传递一些require参数....

public void showAlertDialog(Context context,String title,String message,                                 布尔状态){

    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();
}

答案 2 :(得分:0)

这是调用API的Bast方式

{
   "type":"SUCCESS",
   "msg":"Container RBFFiyatlama2_1.0.1 successfully called.",
   "result":{
      "execution-results":{
         "results":[
            {
               "value":2,
               "key":""
            },
            {
               "value":{
                  "com.myteam.rbffiyatlama2.Employee":{
                     "salary":2400.0,
                     "age":35,
                     "cofactor":0.2
                  }
               },
               "key":"Employee0"
            },
            {
               "value":{
                  "com.myteam.rbffiyatlama2.Employee":{
                     "salary":4800.0,
                     "age":35,
                     "cofactor":0.2
                  }
               },
               "key":"Employee1"
            }
         ],
         "facts":[
            {
               "value":{
                  "org.drools.core.common.DefaultFactHandle":{
                     "external-form":"0:88:1504512052:1504512052:160:DEFAULT:NON_TRAIT:com.myteam.rbffiyatlama2.Employee"
                  }
               },
               "key":"Employee0"
            },
            {
               "value":{
                  "org.drools.core.common.DefaultFactHandle":{
                     "external-form":"0:89:213603577:213603577:159:DEFAULT:NON_TRAIT:com.myteam.rbffiyatlama2.Employee"
                  }
               },
               "key":"Employee1"
            }
         ]
      }
   }
}

在API主叫方

public class Employee
{
    public int age { get; set; }
    public double cofactor { get; set; }
    public int salary { get; set; }
}

和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();
        }
    });
}

答案 3 :(得分:0)

尝试此代码。 在此代码中,在一个类中完成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());
        }
    });