Подтвердить что ты не робот

Как установить тайм-аут в библиотеке дооснащения?

Я использую Retrofit библиотеку в своем приложении, и я бы хотел установить тайм-аут в 60 секунд. Есть ли у Дооснащения какой-то способ сделать это?

Я устанавливаю Retrofit следующим образом:

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(BuildConfig.BASE_URL)
    .setConverter(new GsonConverter(gson))
    .build();

Как установить таймаут?

4b9b3361

Ответ 1

Вы можете установить таймауты на базовом HTTP-клиенте. Если вы не укажете клиента, Retrofit создаст один из них со стандартным подключением и таймаутом чтения. Чтобы настроить собственные таймауты, вам необходимо настроить свой собственный клиент и предоставить его RestAdapter.Builder.

Опция заключается в использовании клиента OkHttp, также из Square.

1. Добавить зависимость библиотеки

В build.gradle включить эту строку:

compile 'com.squareup.okhttp:okhttp:x.x.x'

Где x.x.x - желаемая версия библиотеки.

2. Задайте клиенту

Например, если вы хотите установить тайм-аут в 60 секунд, сделайте этот способ для доработки до версии 2 и Okhttp до версии 3 (ДЛЯ НОВЫХ ВЕРСИЙ, ВИДИТЕ РЕДАКТИРОВАНИЕ):

public RestAdapter providesRestAdapter(Gson gson) {
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

    return new RestAdapter.Builder()
        .setEndpoint(BuildConfig.BASE_URL)
        .setConverter(new GsonConverter(gson))
        .setClient(new OkClient(okHttpClient))
        .build();
}

РЕДАКТИРОВАТЬ 1

Для версий okhttp с 3.x.x вам необходимо установить зависимость следующим образом:

compile 'com.squareup.okhttp3:okhttp:x.x.x'

И установите клиент, используя шаблон построителя:

final OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .build();

Дополнительная информация в Timeouts


РЕДАКТИРОВАТЬ 2

Обновленные версии, так как 2.x.x также использует шаблон построителя, поэтому измените блок возврата выше на это:

return new Retrofit.Builder()
    .baseUrl(BuildConfig.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build();

Если вы используете такой код, как мой метод providesRestAdapter, измените тип возвращаемого метода на Retrofit.

Дополнительная информация в Дооснащение 2 - Руководство по обновлению от 1.9


ps: Если ваша minSdkVersion больше 8, вы можете использовать TimeUnit.MINUTES:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);

Подробнее об устройствах см. TimeUnit.

Ответ 2

Эти ответы были устаревшими для меня, так вот как это получилось.

Добавьте OkHttp, в моем случае версия 3.3.1:

compile 'com.squareup.okhttp3:okhttp:3.3.1'

Затем, прежде чем строить свою доработку, сделайте следующее:

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .build();
return new Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Ответ 3

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();


                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}

@FormUrlEncoded
@POST("architect/project_list_Design_files")
Call<DesignListModel> getProjectDesign(
        @Field("project_id") String project_id);


@Multipart
@POST("architect/upload_design")
Call<BoqListModel> getUpLoadDesign(
        @Part("user_id") RequestBody user_id,
        @Part("request_id") RequestBody request_id,
        @Part List<MultipartBody.Part> image_file,
        @Part List<MultipartBody.Part> design_upload_doc);


private void getMyProjectList()
{

    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
    Call<MyProjectListModel> call = apiService.getMyProjectList("",Sorting,latitude,longitude,Search,Offset+"",Limit);
    call.enqueue(new Callback<MyProjectListModel>() {
        @Override
        public void onResponse(Call<MyProjectListModel> call, Response<MyProjectListModel> response) {
            try {
                Log.e("response",response.body()+"");

            } catch (Exception e)
            {
                Log.e("onResponse: ", e.toString());
                           }
        }
        @Override
        public void onFailure(Call<MyProjectListModel> call, Throwable t)
        {
            Log.e( "onFailure: ",t.toString());
                   }
    });
}

// file upload

private void getUpload(String path,String id)
    {

        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        MultipartBody.Part GalleryImage = null;
        if (path!="")
        {
            File file = new File(path);
            RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            GalleryImage = MultipartBody.Part.createFormData("image", file.getName(), reqFile);
        }

        RequestBody UserId = RequestBody.create(MediaType.parse("text/plain"), id);
        Call<uplod_file> call = apiService.geUplodFileCall(UserId,GalleryImage);
        call.enqueue(new Callback<uplod_file>() {
            @Override
            public void onResponse(Call<uplod_file> call, Response<uplod_file> response) {
                try {
                    Log.e("response",response.body()+"");
                    Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();

                } catch (Exception e)
                {
                    Log.e("onResponse: ", e.toString());
                }
            }
            @Override
            public void onFailure(Call<uplod_file> call, Throwable t)
            {
                Log.e( "onFailure: ",t.toString());
            }
        });
    }

    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Ответ 4

Я использую Retrofit 1.9, чтобы получить XML.

public class ServicioConexionRetrofitXML {

    public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
    public static final long tiempoMaximoRespuestaSegundos = 60;
    public static final long tiempoMaximoLecturaSegundos = 100;
    public static final OkHttpClient clienteOkHttp = new OkHttpClient();


    private static RestAdapter.Builder builder = new RestAdapter.Builder().
            setEndpoint(API_BASE_URL).
            setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());


    public static <S> S createService(Class<S> serviceClass) {
        clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
        clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }

}

Если вы используете Retrofit 1.9.0 и okhttp 2.6.0, добавьте в свой файл Gradle.

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    // Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
    // en conflicto.
    compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }

Примечание. Если вам нужно получить JSON, просто удалите из кода выше.

.setConverter(new SimpleXMLConverter())

Ответ 5

Для Retrofit1.9 с пользователями OkHttp3, вот решение,

.setClient(new Ok3Client(new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build()))

Ответ 6

public class ApiModule {
    public WebService apiService(Context context) {
        String mBaseUrl = context.getString(BuildConfig.DEBUG ? R.string.local_url : R.string.live_url);

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectTimeout(120, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                //.addNetworkInterceptor(networkInterceptor)
                .build();

        return new Retrofit.Builder().baseUrl(mBaseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build().create(WebService.class);

    }
}

Ответ 7

Это будет лучший способ установить тайм-аут для каждой службы (передача таймаута как параметра)

public static Retrofit getClient(String baseUrl, int serviceTimeout) {
        Retrofit retrofitselected = baseUrl.contains("http:") ? retrofit : retrofithttps;
        if (retrofitselected == null || retrofitselected.equals(retrofithttps)) {
            retrofitselected = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(getGson().create()))
                    .client(!BuildConfig.FLAVOR.equals("PRE") ? new OkHttpClient.Builder()
                            .addInterceptor(new ResponseInterceptor())
                            .connectTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
                            .writeTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
                            .readTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
                            .build() : getUnsafeOkHttpClient(serviceTimeout))
                    .build();
        }
        return retrofitselected;
    }

И не пропустите это для OkHttpClient.

private static OkHttpClient getUnsafeOkHttpClient(int serviceTimeout) {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            OkHttpClient okHttpClient = builder
                    .addInterceptor(new ResponseInterceptor())
                    .connectTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
                    .writeTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
                    .readTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
                    .build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

Надеюсь, это поможет любому.

Ответ 8

Я нашел этот пример

https://github.com/square/retrofit/issues/1557

Здесь мы устанавливаем клиентский клиент клиентского подключения клиента прежде, чем мы создадим реализацию обслуживания API-сервиса.

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import retrofit.Endpoint
import retrofit.RestAdapter
import retrofit.client.Request
import retrofit.client.UrlConnectionClient
import retrofit.converter.GsonConverter


class ClientBuilder {

    public static <T> T buildClient(final Class<T> client, final String serviceUrl) {
        Endpoint mCustomRetrofitEndpoint = new CustomRetrofitEndpoint()


        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
        RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(mCustomRetrofitEndpoint)
            .setConverter(new GsonConverter(gson))
            .setClient(new MyUrlConnectionClient())
        RestAdapter restAdapter = builder.build()
        return restAdapter.create(client)
    }
}

 public final class MyUrlConnectionClient extends UrlConnectionClient {
        @Override
        protected HttpURLConnection openConnection(Request request) {
            HttpURLConnection connection = super.openConnection(request);
            connection.setConnectTimeout(15 * 1000);
            connection.setReadTimeout(30 * 1000);
            return connection;
        }
    }

Ответ 9

    public class ApiClient {
        private static Retrofit retrofit = null;
        private static final Object LOCK = new Object();

        public static void clear() {
            synchronized (LOCK) {
                retrofit = null;
            }
        }

        public static Retrofit getClient() {
            synchronized (LOCK) {
                if (retrofit == null) {

                    Gson gson = new GsonBuilder()
                            .setLenient()
                            .create();

                    OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                            .connectTimeout(40, TimeUnit.SECONDS)
                            .readTimeout(60, TimeUnit.SECONDS)
                            .writeTimeout(60, TimeUnit.SECONDS)
                            .build();

                    // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                    retrofit = new Retrofit.Builder()
                            .client(okHttpClient)
                            .baseUrl(Constants.WEB_SERVICE)
                            .addConverterFactory(GsonConverterFactory.create(gson))
                            .build();
                }
                return retrofit;
            }'enter code here'

        }

        public static RequestBody plain(String content) {
            return getRequestBody("text/plain", content);
        }

        public static RequestBody getRequestBody(String type, String content) {
            return RequestBody.create(MediaType.parse(type), content);
        }
    }


    -------------------------------------------------------------------------


        implementation 'com.squareup.retrofit2:retrofit:2.4.0'
        implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

-----------------------------------------------------------------------------
interface calling 

    @FormUrlEncoded
    @POST("user/user_login")
    Call<UserRegistrationModel> getUserLogin(
            @Field("email") String email,
            @Field("password") String password,
            @Field("user_device_token") String user_device_token,
            @Field("user_device_type") String user_device_type);'enter code here'

Ответ 10

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }'enter code here'

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'