Android Retrofit2增加超时连接

时间:2018-06-29 09:18:05

标签: android retrofit2

我正在构建服务,以使用Retrofit2通过Android中的Web服务发送数据。

现在这是代码:

private void checkUnsyncedRecords() {

        final DbLayer db = DatabaseHelper.getDatabase(getApplicationContext(), false);

        LinkedList<SensorData> listaDatiUnsunc = db.fetchSensorData(null, false);


        WebService webService = WebServiceHandler.getService();


        //endregion

        //region Alerts
        if (listaDatiUnsunc.size() > 0) {

            JsonArray readAlerts = new GsonBuilder().create().toJsonTree(listaDatiUnsunc).getAsJsonArray();

            //create request body
            JsonObject body = WebServiceHandler.getDefaultBody();
            body.addProperty(WebServiceHandler.ID_CLINICAL_DOCUMENT, 70);
            body.add(WebServiceHandler.VALORI, readAlerts);
            //Log.i(TAG, body.toString());
            try {
                Call<BaseMessage<JsonElement>> request = webService.insertDatiCalza(body);
                Response<BaseMessage<JsonElement>> response = request.execute();

                if (response.isSuccessful()) {
                    BaseMessage<JsonElement> message = response.body();
                    if (message != null) {
                        if (message.getStatus() == MessageStatus.SUCCESS) {
                            Log.d(TAG, "SensorValue sync succeeded");

                            //AGGIORNO LO STATO DI AGGIORNAMENTO DI TUTTE LE RILEVAZIONI
                            for (SensorData sens: listaDatiUnsunc) {
                                sens.setSync(true);
                                db.updateSensorData(sens);
                            }
                        } else {
                            Log.e(TAG, "SensorValue sync failed: " + message.getMessage() +
                                    " (code: " + message.getStatus() + ")");
                        }
                    } else {
                        Log.e(TAG, "SensorValue sync: reply message is null.");
                    }
                } else {
                    Log.e(TAG, "SensorValue sync: request failed (code: " +
                            response.code() + ", body: " + response.message() + ").");
                }
            } catch (Exception e) {
                Log.e(TAG, "SensorValue sync call", e);
            } finally {

            }
        }
        //endregion


    }

此代码有效,但有时LinkedList包含更多值,并且如果它的大小很大,我将遇到此异常。

java.net.SocketTimeoutException

现在有一种增加超时连接的方法吗?

  

编辑   这是我的Retrofit类的实例:

public static WebService getService() {

        if (webService == null) {
            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();
            Retrofit retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create(gson)).baseUrl(BASE_URL).build();
            webService = retrofit.create(WebService.class);
        }

        return webService;
    }

1 个答案:

答案 0 :(得分:2)

您可以通过在用于构建OkHttpClient实例的retrofit中指定不同的超时来增加超时。

val okhttpclient = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(15, TimeUnit.SECONDS);
        .build()

并使用它来创建改造实例。

Retrofit.Builder()
       .baseUrl(baseUrl)
       .addConverterFactory(GsonConverterFactory.create(gson))
       .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
       .callFactory(httpClientBuilder.build())
       .build()

修改

使用它来生成您的WebService

public static WebService getService() {

    if (webService == null) {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        OkHttpClient okhttpclient = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS);
            .build()

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson)).baseUrl(BASE_URL).callFactory(okhttpclient).build();
        webService = retrofit.create(WebService.class);
    }

    return webService;
}