Tuesday, 22 May 2018

Retrofite

public class ApiClient {

    public static OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @Override                public Response intercept(Chain chain) throws IOException {

                    Request.Builder builder = chain.request().newBuilder();

                    builder.addHeader("Accept", "application/json");
                    builder.addHeader("x-wsse", AppController.getInstance().getHeader());

                    return chain.proceed(builder.build());
                }
            }).connectTimeout(CONNECTION_TIME_OUT_IN_SECOND, TimeUnit.SECONDS)
            .writeTimeout(CONNECTION_TIME_OUT_IN_SECOND, TimeUnit.SECONDS)
            .readTimeout(CONNECTION_TIME_OUT_IN_SECOND, TimeUnit.SECONDS)
            .build();

    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BaseUrl)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }


    public static retrofit2.Call getAPI(String url, retrofit2.Callback<ResponseBody> callback) {

        ApiInterface apiCall = getClient().create(ApiInterface.class);

        retrofit2.Call call = apiCall.CommonGet(url);

        call.enqueue(callback);

        return call;

    }

    public static retrofit2.Call deleteAPI(String url, retrofit2.Callback<ResponseBody> callback) {

        ApiInterface apiCall = getClient().create(ApiInterface.class);

        retrofit2.Call call = apiCall.CommonDelete(url);

        call.enqueue(callback);

        return call;

    }


}


public interface ApiInterface {

    //Common Multipart API    @POST    @Multipart    Call<ResponseBody> CommonPostMultipart(@Url String url, @PartMap HashMap<String, RequestBody> map);


    @POST    Call<ResponseBody> CommonPost(@Url String url);

    @POST    @FormUrlEncoded    Call<ResponseBody> CommonPostWithMap(@Url String url, @FieldMap HashMap<String, String> map);

    // Common Get API    @GET    Call<ResponseBody> CommonGet(@Url String url);

    //Common PATCH API    @PATCH    @FormUrlEncoded    Call<ResponseBody> CommonPatch(@Url String url, @FieldMap HashMap<String, String> map);

    //Common PATCH API    @DELETE    Call<ResponseBody> CommonDelete(@Url String url);
}

No comments:

Post a Comment