Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 改装2中同时存在重复请求_Android_Retrofit_Retrofit2_Okhttp - Fatal编程技术网

Android 改装2中同时存在重复请求

Android 改装2中同时存在重复请求,android,retrofit,retrofit2,okhttp,Android,Retrofit,Retrofit2,Okhttp,我面临一个单一API重复请求的问题, 我使用的是改型2。当我尝试调用一个API时,它会三次击中服务器。 同一API被多次调用,调用的节数不多。代码如下: public Retrofit retrofit() { String UrlBasePath=""; if (mRetrofit == null) { if (builder == null) { builder = new OkHttpClient.Builder();

我面临一个单一API重复请求的问题, 我使用的是改型2。当我尝试调用一个API时,它会三次击中服务器。 同一API被多次调用,调用的节数不多。代码如下:

 public Retrofit retrofit() {
    String UrlBasePath="";

    if (mRetrofit == null) {
        if (builder == null) {
            builder = new OkHttpClient.Builder();
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                HttpUrl httpUrl = original.url().newBuilder()
                        .build();
                String credentials = BuildConfig.ApiUserName + ":" + BuildConfig.ApiPassword;

                if (BuildConfig.ApiUserName.equals("APIUSERNAME") || BuildConfig.ApiPassword.equals("APIPASSWORD")) {
                    AnalyticsManager.sendEvent("RETROERROR", "AUTHENTICATIONFAILED", "FAILED");
                }

                final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
                // Request customization: add request headers
                Request request = original.newBuilder()
                        .addHeader("Authorization", basic)
                        .addHeader("User-Agent", "android")
                        .method(original.method(), original.body())
                        .url(httpUrl)
                        .build();
                return chain.proceed(request);

            }
        }).connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS);

        if(BuildConfig.BUILD_TYPE.equalsIgnoreCase("debug")) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(logging);
        }

        UrlBasePath = UrlParser.httpsUrlBasePath;

        OkHttpClient client = enableTls12OnPreLollipop(builder).build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(UrlBasePath)
                .addConverterFactory(new ToStringConverterFactory())
                .addConverterFactory(GsonConverterFactory.create(gsonMapper()))
                .client(client)
                .build();
    }
    }
    return mRetrofit;
}
在“活动:活动代码”中调用此方法

private final BmApiInterface RetroApiCall = RetroConnect.getInstance().retrofit().create(BmApiInterface.class); //global variable

Call<SingleLoginParser> loginCall = RetroApiCall.getLoginAPI(MatriidDet+"~"+Constants.APPVERSIONCODE,System.currentTimeMillis(),
                        Constants.constructApiUrlMap(new UrlParser().UrlGenerator(Constants.COMMON_LOGIN, new String[]{}))
                );
                mCallList.add(loginCall);
                RetroConnect.getInstance().AddToEnqueue(loginCall, mListener, RequestType.COMMON_LOGIN);
private final BmApiInterface RetroApiCall=RetroConnect.getInstance().reformation().create(BmApiInterface.class)//全局变量
调用loginCall=retropapicall.getLoginAPI(MatriidDet+“~”+常量.APPVERSIONCODE,System.currentTimeMillis(),
ConstructApirlMap(新的UrlParser().UrlGenerator(Constants.COMMON_登录,新字符串[]{}))
);
mCallList.add(loginCall);
RetroConnect.getInstance().addToeQueue(loginCall、mListener、RequestType.COMMON\u LOGIN);

有人能帮我吗

您使用了异步api调用(使用改型),并对改型设置进行了一些更改。 对改装进行单独分类

    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 Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (context == null) {
                request = request
                        .newBuilder()
                        .build();
            } else {
                request = request
                        .newBuilder()
                        .addHeader("Authorization", "Bearer " + AppSetting.getStringSharedPref(context, Constants.USER_KEY_TOKEN, ""))
                        .build();
            }
            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}
然后在为调用创建api接口后,如下所示

public interface ApiInterface {
@POST("api/login")
Call<LoginResponseModel> loginCheck(@Body UserData data);
公共接口{
@POST(“api/登录”)
调用登录检查(@Body UserData);
}

然后像下面的代码一样使用

    ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
    Call<LoginResponseModel> loginResponseModelCall = apiInterface.loginCheck("yourobject or key");
    loginResponseModelCall.enqueue(new Callback<LoginResponseModel>() {
        @Override
        public void onResponse(Call<LoginResponseModel> call, Response<LoginResponseModel> response) {
            if (response != null && response.isSuccessful() && response.body() != null) {
                Toast.makeText(getApplicationContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();

            } else {
            }
        }

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

        }
    });
ApiInterface-ApiInterface=ApiClient.getInstance().getClient().create(ApiInterface.class);
调用loginResponseModelCall=apiInterface.loginCheck(“您的对象或键”);
loginResponseModelCall.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response!=null&&response.issucessful()&&response.body()!=null){
Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
}否则{
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});

当服务器响应缓慢且超时时,retfofit2可能会多次重试同一请求。要防止出现这种情况,您必须对OkHttpClient使用
.retryOnConnectionFailure(false)
方法

示例代码:

OkHttpClient okHttpClient= null;
        okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory(),trustManager)
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .writeTimeout(2, TimeUnit.MINUTES)
                //.sslSocketFactory(sslSocketFactory, trustManager)
                .followRedirects(false)
                .followSslRedirects(false)
                .retryOnConnectionFailure(false)
                .cache(null)//new Cache(sContext.getCacheDir(),10*1024*1024)
                .build();
在以前的版本中,有一些错误并在改装后修复:2.1.0

因此,您应该使用更新版本的Reformation2和okhttp3:

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    implementation 'com.squareup.okhttp3:okhttp:3.4.1' 
议题讨论:


您能在调用该类进行改装的地方共享代码吗?上面添加了活动代码。@sree:您找到解决方案了吗?我也面临着同样的问题。@Jatin,不,我没有找到任何解决方案。。像那样,只有我在使用。在单独的类中进行改装然后我认为若你们并没有放置任何循环和其他后台服务类,那个么这个请求只是一次。如果使用按钮,则每次单击按钮时,请求都会转到服务器。循环意味着什么?改造在哪里?在Activity中,我只调用了一次。当您将request方法放入oncreate方法的Activity类中时,当Activity类调用该时间时,request激发。单击按钮only,我们正在调用request