【问题标题】:Is it possible to use retrofit 1.9.0 and retrofit 2.x simultaneously?是否可以同时使用改造 1.9.0 和改造 2.x?
【发布时间】:2017-07-21 14:28:05
【问题描述】:

我有一个包含许多现有 Retrofit 1.9 接口的应用程序。我想开始 逐步升级到 Retrofit 2.x(一次全部升级目前不可行) 获得对 RxJava 调用适配器的支持(因为 1.9 不再开发)。

让 Retrofit1 的 RestAdapter 共享一个 OkHttp3 客户端相当简单 将在 Retrofit2 接口中使用。版本 1.9 和 2.x 也有 不同的 maven groupIds,因此这些类可以并排存在而没有问题。

但是,我在运行时遇到以下异常:

java.lang.IllegalAccessError: Method 'com.google.gson.stream.JsonWriter com.google.gson.Gson.newJsonWriter(java.io.Writer)' is inaccessible to class 'retrofit2.converter.gson.GsonRequestBodyConverter'

Retrofit 1 对 GSON 2.3.1 有很强的依赖性,所讨论的方法已在 GSON 2.4 中公开。我已经设置了我的 Gradle 依赖项,以便 GSON 依赖项解析为 v2.7(我发布的最新版本):

build.gradle

compile('com.squareup.retrofit:retrofit:1.9.0') {
    exclude module: 'gson'
}
compile 'com.jakewharton.retrofit:retrofit1-okhttp3-client:1.1.0'

compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"
compile "com.squareup.retrofit2:adapter-rxjava:2.3.0"
compile 'com.google.code.gson:gson:2.7'

运行 ./gradlew :app:dependencies 表示正在解析 GSON 2.7,但是运行时行为可疑...

更新:我发现第 3 方硬件 SDK 在其 AAR 中捆绑了 GSON 2.3.1。我不知道如何删除它。

【问题讨论】:

  • 为什么要同时使用这两个?
  • 如问题第一段所述:* RxJava 调用适配器支持 * 1.9 不再开发
  • 是的,我知道。但是您可以为所有人迁移到 Retrofit 2。 RxJava2 已经发布了。甚至 RxJav2-Retrofit2-Adapter github.com/square/retrofit/tree/master/retrofit-adapters/…
  • 正如在第一段中所解释的那样,由于 Retrofit 1.9 中已经编写的代码的大小,现在不能一次转换所有内容。逐步添加新的 retrofit2 端点并随着时间的推移转换旧的端点是我需要能够完成的。
  • 两年多过去了。你的疑惑解决了吗?

标签: java android retrofit retrofit2


【解决方案1】:

我最近在 Retrofit 1.9 旁边实现了 Retrofit 2.9.0,因为版本 2 处理会话的能力要好得多,而且我的一个 API 调用由于缺少处理响应 cookie(会话)而失败。

我有同样的问题,此时将整个项目迁移到 Retrofit 2 是不可行的。不过我可以确认它正在工作。

我将向您展示我是如何实现 1.9 和 2.9.0 的。完整课程的链接见底部。

对于两者: 创建一个类,您可以从中访问您的 Retrofit 对象并调用接口:

public class ApiManager {

private static final String TAG = "API MANAGER";

private static final String API_URL = BuildConfig.API_URL;

private static Gson gson = new GsonBuilder()
    .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
    .setLenient()
    .create();

// The rest of the class to follow

然后具体到 1.9:

private static RequestInterceptor requestInterceptor = new RequestInterceptor() {
    @Override
    public void intercept(RequestInterceptor.RequestFacade request) {
        SessionManager sessionManager = new SessionManager(ContextHandler.getContext());
        HashMap session = sessionManager.getUserDetails();
        Object session_id = session.get("session_id");
        Object token = session.get("token");

        if (session_id != null && token != null) {
            request.addHeader("Cookie", "session_id=" + session_id + ";");
            request.addHeader("Cookie", "token=" + token + ";");
            Log.i("INTERCEPT", "Sent Cookies");
        }
        request.addHeader("Accept", "application/json");
    }
};

public static OkHttpClient getClient() {

    // init okhttp 3 logger
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    JavaNetCookieJar jncj = new JavaNetCookieJar(CookieHandler.getDefault());


    OkHttpClient client = new OkHttpClient();

    client.newBuilder()
            .addInterceptor(new AddCookiesInterceptor(ContextHandler.getContext()))
            .addInterceptor(new ReceivedCookiesInterceptor(ContextHandler.getContext()))
            .addNetworkInterceptor(logging)
            .cookieJar(jncj)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.MINUTES);

    return client;
}

private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
    .setEndpoint(API_URL) // On device
    .setRequestInterceptor(requestInterceptor)
    .setClient(new Ok3Client(getClient()))
    .setConverter(new GsonConverter(gson))
    .setLogLevel(RestAdapter.LogLevel.FULL) //log the request
    .build();


public interface AuthenticationInterface {
    @Headers("Content-type: application/json")
    @POST("/auth/getsession")
    void Authenticate(@Body Authentication Auth, Callback<SessionStore> response);

    @Headers("Content-type: application/json")
    @GET("/auth/logout")
    void logout(Callback<String> response);

    @Headers("Content-type: application/json")
    @GET("/auth/logout")
    String logout();
}


// Bind REST_ADAPTER to Interface
public static final AuthenticationInterface AUTHENTICATION_INTERFACE = REST_ADAPTER.create(AuthenticationInterface.class);
// Use this when you want to run the request.
public static AuthenticationInterface getAuthenticationService(){ return AUTHENTICATION_INTERFACE;  }

所以你会使用上面的如下:

ApiManager.getAuthenticationService().Authenticate(auth, new Callback<SessionStore>() {

    @Override
    public void success(SessionStore sessionStore, Response response) {
        // Do somthing

    }

    @Override
    public void failure(RetrofitError error) {
        // Handle Error
    }
});

对于 2.9.0:

public static OkHttpClient getHeader() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient okClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addInterceptor(new AddCookiesInterceptor(ContextHandler.getContext())) 
            .addInterceptor(new ReceivedCookiesInterceptor(ContextHandler.getContext())) 
            .cookieJar(cookieJar)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.MINUTES)
            .addNetworkInterceptor(
                    new Interceptor() {
                        @Override
                        public Response intercept(Interceptor.Chain chain) throws IOException {
                            Request request = null;
                                Log.d("--Authorization-- ", "authorizationValue");

                            Request original = chain.request();
                            // Request customization: add request headers
                            Request.Builder requestBuilder = original.newBuilder();


                            SessionManager sessionManager = new SessionManager(ContextHandler.getContext());

                            HashMap session = sessionManager.getUserDetails();
                            Object session_id = session.get("session_id");
                            Object token = session.get("token");

                            if (session_id != null && token != null) {
                                requestBuilder.addHeader("Cookie", "session_id=" + session_id + ";");
                                requestBuilder.addHeader("Cookie", "token=" + token + ";");
                                Log.i("INTERCEPT", "Sent Cookies");
                            }
                            requestBuilder.addHeader("Accept", "application/json");

                                request = requestBuilder.build();

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

}

private static final Retrofit REST_ADAPTER2 = new Retrofit.Builder()
    .baseUrl(API_URL) // On device
    .client(getHeader())
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

public interface JasperReportsInterface {

    /**
     *
     * @param agent_id
     * @param report_id
     */
    @retrofit2.http.Headers("Content-type: application/json")
    @retrofit2.http.GET("/agents/{agent_id}/reports/{report_id}/")
    Call<Reports> GetAgentReportView(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id);

    /**
     *
     * @param agent_id
     * @param report_id
     */
    @retrofit2.http.Headers("Content-type: application/json")
    @retrofit2.http.GET("/agents/{agent_id}/reports/{report_id}/jobs")
    Call<Jobs> PollAgentReportData(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id);

    /**
     *
     * @param agent_id
     * @param report_id
     * @param jsonBody
     */
    @retrofit2.http.Headers("Content-type: application/json")
    @retrofit2.http.POST("/agents/{agent_id}/reports/{report_id}/jobs")
    Call<String> PostAgentReportData(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id, @retrofit2.http.Body JsonObject jsonBody);

    /**
     *
     * @param agent_id
     * @param report_id
     * @param jsonBody
     */
    @retrofit2.http.Headers("Content-type: application/json")
    @retrofit2.http.POST("/agents/{agent_id}/reports/{report_id}/jobs")
    Call<String> DownloadAgentReportData(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id, @retrofit2.http.Body JsonObject jsonBody);




}
// Bind REST_ADAPTER2 to Interface
public static final JasperReportsInterface JASPER_REPORTS_INTERFACE = REST_ADAPTER2.create(JasperReportsInterface.class);
// Use this when you want to run the request.
public static JasperReportsInterface getJasperReportsService(){  return JASPER_REPORTS_INTERFACE;  }

您可以按以下方式使用上述内容:

Call<Reports> reportsCall = ApiManager.getJasperReportsService().GetAgentReportView(agentsID, reportTypeID);
reportsCall.enqueue(new retrofit2.Callback<Reports>() {
    @Override
    public void onResponse(Call<Reports> call, retrofit2.Response<Reports> response) {
        if(response.isSuccessful()) {
            report = response.body();

        } else {
            int statusCode = response.code();

            // handle request errors yourself
            ResponseBody errorBody = response.errorBody();
        }

    }

    @Override
    public void onFailure(Call<Reports> call, Throwable t) {

    }
});

您需要的依赖项分别是 1.9 和 2 所需的基本依赖项。

请参阅here 了解完整课程。

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2018-04-25
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多