我是重新装修图书馆的新手。我正在开发一个应用程序,在其中我必须进行多个API调用,但是当我尝试进行第一个API调用时,这个问题一直困扰着我.
我所面临的问题是,每当我使用调用retrofit的异步调用方法时,onResponse方法中的功能将运行2次.
当我异步调用API调用时,这是我的代码.
final ApiModule apiService = ApiServiceGenerator.createService(ApiModule.class);
Call <ConfigResponse> call = apiService.getConfig();
call.enqueue(new Callback<ConfigResponse>() {
@Override
public void onResponse(Call<ConfigResponse> call, Response<ConfigResponse> response) {
try {
if (response.isSuccessful()) {
Log.e("MyTag", "This is running");
}
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ConfigResponse> call, Throwable t) {
e.printStackTrace();
}
});一旦我在设备上运行了应用程序,当我看到我的android工作室的记录器时,它就把日志消息显示为-
E/MyTag: This is running
E/MyTag: This is running在这里看来它跑了两次!
我不明白为什么它要跑两次。请帮我解决这个..。
只是为了更多的帮助..。我像这样实现了我的代码。
ApiModule接口(在这里我定义了API调用URL)
public abstract interface ApiModule {
@GET("config")
Call<ConfigResponse> getConfig();
}ApiServiceGenerator是这样的-
public class ApiServiceGenerator {
public static final String API_BASE_URL = "https://www.example.com/";
private static OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder().addHeader("App-Secret", "some-secret-key").build();
return chain.proceed(newRequest);
}
})
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) // Just For logging
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new ArrayAdapterFactory())
.create();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create()));
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
public static Retrofit retrofit() { // For Error Handing when non-OK response is received from Server
OkHttpClient httpClient = new OkHttpClient.Builder().build();
OkHttpClient client = httpClient;
return builder.client(client).build();
}
}发布于 2016-04-11 14:36:40
最后我解决了我的问题。这不是改造图书馆的问题!
其实是我的错。我要打开片段两次(在回答这个问题之前我不知道).这就是为什么代码片段中的代码运行了两次,这使我认为作为改造响应运行两次..。
发布于 2019-10-29 16:39:10
在我的例子中,我使用的是拦截器,在其中一个拦截器中,我两次调用chain.proceed()。也许你也应该检查一下。这将不会出现在您的日志中。使用Stetho检查一个电话到底打了多少次。
不要在任何拦截器中多次调用任何来自retrofit的函数,该函数会多次返回“响应”。
发布于 2021-02-23 04:49:38
在我的例子中,由于chain.proceed(请求)在同一个拦截器中调用了两次,它被调用了两次
例如
class ErrorInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
chain.proceed(request)
val response = chain.proceed(request) // it called twice in this Interceptor
when (response.code()) {
}
return response
}
}https://stackoverflow.com/questions/36546482
复制相似问题