简体   繁体   English

Retrofit库如何设置超时?

[英]How to set timeout in Retrofit library?

I am using Retrofit library in my app, and I'd like to set a timeout of 60 seconds.我在我的应用程序中使用Retrofit库,我想将超时设置为 60 秒。 Does Retrofit have some way to do this? Retrofit 有办法做到这一点吗?

I set Retrofit this way:我这样设置 Retrofit:

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

How can I set the timeout?如何设置超时?

You can set timeouts on the underlying HTTP client.您可以在底层 HTTP 客户端上设置超时。 If you don't specify a client, Retrofit will create one with default connect and read timeouts.如果您不指定客户端,Retrofit 将创建一个具有默认连接和读取超时的客户端。 To set your own timeouts, you need to configure your own client and supply it to the RestAdapter.Builder .要设置自己的超时,您需要配置自己的客户端并将其提供给RestAdapter.Builder

An option is to use the OkHttp client, also from Square.一种选择是使用同样来自 Square 的OkHttp客户端。

1. Add the library dependency 1.添加库依赖

In the build.gradle, include this line:在 build.gradle 中,包含以下行:

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

Where xxx is the desired library version.其中xxx是所需的库版本。

2. Set the client 2.设置客户端

For example, if you want to set a timeout of 60 seconds, do this way for Retrofit before version 2 and Okhttp before version 3 ( FOR THE NEWER VERSIONS, SEE THE EDITS ):例如,如果您想将超时设置为 60 秒,请对版本 2 之前的 Retrofit 和版本 3 之前的 Okhttp 执行此操作(对于较新的版本,请参阅编辑):

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();
}

EDIT 1编辑 1

For okhttp versions since 3.xx , you have to set the dependency this way:对于3.xx okhttp 版本,您必须以这种方式设置依赖项:

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

And set the client using the builder pattern:并使用构建器模式设置客户端:

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

More info in Timeouts超时中的更多信息


EDIT 2编辑 2

Retrofit versions since 2.xx also uses the builder pattern, so change the return block above to this:2.xx以来的改造版本也使用构建器模式,因此将上面的返回块更改为:

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

If using a code like my providesRestAdapter method, then change the method return type to Retrofit .如果使用像我的providesRestAdapter方法这样的代码,则将方法返回类型更改为Retrofit

More info in Retrofit 2 — Upgrade Guide from 1.9Retrofit 2 中的更多信息— 从 1.9 升级指南


ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES : ps:如果你的 minSdkVersion 大于 8,你可以使用TimeUnit.MINUTES

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

For more details about the units, see TimeUnit .有关单位的更多详细信息,请参阅TimeUnit

These answers were outdated for me, so here's how it worked out.这些答案对我来说已经过时了,所以这是如何解决的。

Add OkHttp, in my case the version is 3.3.1 :添加 OkHttp,就我而言,版本是3.3.1

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

Then before building your Retrofit, do this:然后在构建您的改造之前,请执行以下操作:

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();
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'

In Kotlin:在 Kotlin 中:

At first you should create a OkHttp client and add in Retrofit builder首先你应该创建一个OkHttp client并添加 Retrofit builder

fun create(): Retrofit { 

        val client = OkHttpClient.Builder()
            .readTimeout(60,TimeUnit.SECONDS)
            .build()


        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}

I am using Retrofit 1.9 to obtain a XML .我正在使用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);
    }

}

If you are using Retrofit 1.9.0 and okhttp 2.6.0, add to your Gradle file.如果您使用的是 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'
    }

Note: If you need to fetch a JSON , just remove from code above.注意:如果您需要获取JSON ,只需从上面的代码中删除即可。

.setConverter(new SimpleXMLConverter())

对于使用 OkHttp3 用户的 Retrofit1.9,这里是解决方案,

.setClient(new Ok3Client(new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build()))
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);

    }
}

This will be the best way, to set the timeout for each service (passing timeout as parameter)这将是最好的方法,为每个服务设置超时(将超时作为参数传递)

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;
    }

And dont miss this for OkHttpClient.并且不要错过 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);
        }
    }

Hope this will help anyone.希望这会帮助任何人。

I found this example我找到了这个例子

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

Here we set custom url client connection client before before we build API rest service implementation.这里我们在构建 API 休息服务实现之前设置自定义 url 客户端连接客户端。

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;
        }
    }

In Kotlin you can Configure timeout for retrofit2 by在 Kotlin 中,您可以通过以下方式为retrofit2 2 配置超时

create OkHttpClient object创建 OkHttpClient object

val okHttpClient = OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .build()

Then add this object to your retrofit builder然后将此 object 添加到您的 retrofit 构建器

val retrofit = Retrofit.Builder()
    .addConverterFactory(ScalarsConverterFactory.create())
    .client(okHttpClient)
    .baseUrl(BASE_URL)
    .build()

And import TimeUnit from this package并从此 package 导入TimeUnit

import java.util.concurrent.TimeUnit
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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM