Retrofit2拦截器调用2 API

时间:2018-05-09 09:39:09

标签: android retrofit2 interceptor

我正在尝试调用API来获取Cookie,然后调用另一个API来发送请求。

问题是我有很多API,而且每个都需要双重调用 getCookie和if isSuccessfull我可以调用第2个API

我正在阅读有关拦截器的内容,但我该如何使用它?

现在我需要这样做:

 ApiUtil.validateAuthCookie(authCookieModel.getCookie()).enqueue(new Callback<ValidateAuthCookieModel>() {
        @Override
        public void onResponse(Call<ValidateAuthCookieModel> call, Response<ValidateAuthCookieModel> response) {
            if (response.isSuccessful() && response.body().valid)
                ApiUtil.addLike(item.getId(), mCookie).enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                        }
                    });
            else {
                openLogin();
            }
        }

        @Override
        public void onFailure(Call<ValidateAuthCookieModel> call, Throwable t) {
            openLogin();
        }
    });

3 个答案:

答案 0 :(得分:0)

喜欢这个?但我不知道是否可以这样做

public class ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        // original request
        Request request = chain.request();

        // new request
        Request newRequest = ApiUtil.validateAuthCookie("123456789").request();
        // new response
        Response newResponse = chain.proceed(newRequest);

        if (newResponse.code() == 200) {
            return chain.proceed(request);
        } else {
            logout();
            return null;
        }
    }

}

答案 1 :(得分:0)

请按照我与您分享的步骤,这是一种有效的做事方式。 确保首先在您的活动或片段中实现ResponseHandler。

实施ResponseHandler: -

public class SettingsActivity extends Activity implements ResponseHandler {}

致电api: -

//AppManager is my application class of project.
         new RestCaller(SettingsActivity.this, 
AppManager.getRestClient().pushNotification("auth_token", status), 1);

响应: -

    @Override
    public void onSuccess(Call call, Response response, int reqCode) {

        Utility.dismissProgressDialog(progressDialog);
        if (reqCode == 1) {
        //call another api like I mentioned above with other request code
}
}

这是ApiInterface类。

public interface ApiInterface {

    @GET("updateNotificationClinic")
    Call<UpdateClinic> pushNotification(@Query("auth_token") String token,
                                        @Query("pushNotification") String push);

}

创建此类。

 public interface ResponseHandler {

        void onSuccess(Call call, Response response, int reqCode);

        void onFailure(Call call, GenericResponse error, int reqCode);

        void onApiCrash(Call call, Throwable t, int reqCode);
    }

创建RestCaller类。

public class RestCaller {

private int REQ_CODE = 0;
ResponseHandler handler;

    public RestCaller(ResponseHandler context, Call caller, final int REQUEST_CODE) throws NumberFormatException {
        if (REQUEST_CODE <= 0) {
            NumberFormatException ex = new NumberFormatException();
            throw ex;
        }
        REQ_CODE = REQUEST_CODE;
        handler = context;
        ENQUE(caller);
    }

  private void ENQUE(Call call) {
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.code() == 200 | response.code() == 201) {
                    handler.onSuccess(call, response, REQ_CODE);
                } else if (response.code() == 403) {
                    Toast.makeText(AppManager.getAppContext(), "Code: 403", Toast.LENGTH_SHORT).show();
                } else {
                    GenericResponse error = null;
                    Converter<ResponseBody, GenericResponse> errorConverter =
                            AppManager.getRetrofit().responseBodyConverter(GenericResponse.class, new Annotation[0]);
                    try {
                        error = errorConverter.convert(response.errorBody());
                    } catch (IOException e) {}
                    if (error != null)
                        handler.onFailure(call, error, REQ_CODE);
                    else
                        handler.onApiCrash(call, new Throwable(response.raw().message()), REQ_CODE);
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                if (t instanceof UnknownHostException)
                    handler.onApiCrash(call, new Throwable("Unable to access server. Please check your connection."), REQ_CODE);
                else
                    handler.onApiCrash(call, t, REQ_CODE);
            }
        });
    }


   }

创建RetroClient类。

public class RetroClient {
    private Retrofit retrofit = null;
    private static RetroClient object;
private RetroClient() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.readTimeout(60, TimeUnit.SECONDS);
    httpClient.connectTimeout(60, TimeUnit.SECONDS);

    httpClient.addInterceptor(logging.setLevel(HttpLoggingInterceptor.Level.BODY));
    retrofit = new Retrofit.Builder()
            .baseUrl(Config.retrofit_base_url)
            .addConverterFactory(StringConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();
    service = retrofit.create(ApiInterface.class);
}

public static RetroClient getRetroClient() {
    if (object == null) {
        object = new RetroClient();
    } else if (object != null && !object.getRetrofit().baseUrl().toString().equalsIgnoreCase(Config.retrofit_base_url)) {
        object = new RetroClient();
    }
    return object;
}

//this is your class where you set your api's.
    private ApiInterface service;

    public ApiInterface getApiServices() {
        return object.service;
    }

    public Retrofit getRetrofit() {
        return object.retrofit;
    }
}

在您的应用程序类中设置这些方法。

public static ApiInterface getRestClient() {
    return RetroClient.getRetroClient().getApiServices();
}


public static Retrofit getRetrofit() {
    return RetroClient.getRetroClient().getRetrofit();
}

答案 2 :(得分:0)

我有一个解决方案

public Response intercept(Chain chain) throws IOException {
    AuthCookieModel authCookieModel = (AuthCookieModel) FileManager.readObjectPref(MyApplication.getAppContext(), Constants.GENERAL_PREFERENCES, Constants.PREFERENCES_AUTH_COOKIE, AuthCookieModel.class, null);

    // original request
    Request request = chain.request();

    retrofit2.Response<ValidateAuthCookieModel> newResponse = ApiUtil.validateAuthCookie(authCookieModel.getCookie()).execute();
    if (newResponse.isSuccessful() && newResponse.body().valid) {
        // continue with original request
        return chain.proceed(request);
    } else {
        openLogin();

        // problem is HERE, because I need to stop or cancel the chain
       return new Response.Builder()
            .code(600) //Simply put whatever value you want to designate to aborted request.
            .protocol(Protocol.HTTP_2)
            .message("token expired")
            .request(chain.request())
            .build();
    }
}