如何在Retrofit库中设置超时?

and*_*vil 165 java android timeout retrofit

我在我的应用程序中使用Retrofit库,我想将超时设置为60秒.Retrofit有办法做到这一点吗?

我这样设置Retrofit:

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(BuildConfig.BASE_URL)
    .setConverter(new GsonConverter(gson))
    .build();
Run Code Online (Sandbox Code Playgroud)

如何设置超时?

and*_*vil 298

您可以在底层HTTP客户端上设置超时.如果您未指定客户端,则Retrofit将创建一个具有默认连接和读取超时的客户端.要设置自己的超时,您需要配置自己的客户端并将其提供给RestAdapter.Builder.

一个选项是使用来自Square 的OkHttp客户端.

1.添加库依赖项

在build.gradle中,包含以下行:

compile 'com.squareup.okhttp:okhttp:x.x.x'
Run Code Online (Sandbox Code Playgroud)

x.x.x所需的库版本在哪里.

2.设置客户端

例如,如果要设置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();
}
Run Code Online (Sandbox Code Playgroud)

编辑1

对于okhttp版本3.x.x,您必须以这种方式设置依赖关系:

compile 'com.squareup.okhttp3:okhttp:x.x.x'
Run Code Online (Sandbox Code Playgroud)

并使用构建器模式设置客户端:

final OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .build();
Run Code Online (Sandbox Code Playgroud)

更多信息在超时


编辑2

因为改造版本2.x.x也使用了构建器模式,所以将上面的返回块更改为:

return new Retrofit.Builder()
    .baseUrl(BuildConfig.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build();
Run Code Online (Sandbox Code Playgroud)

如果使用类似我的providesRestAdapter方法的代码,则将方法返回类型更改为Retrofit.

更多信息在Retrofit 2 - 升级指南1.9


ps:如果你的minSdkVersion大于8,你可以使用TimeUnit.MINUTES:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)

有关单位的更多详细信息,请参阅TimeUnit.

  • @ Lion789查看已编辑的问题. (2认同)
  • 我正在使用 okhttp3,对我来说我使用了这个代码: new okhttp3.OkHttpClient().newBuilder(); okHttpClient.readTimeout(60, TimeUnit.SECONDS); okHttpClient.writeTimeout(60, TimeUnit.SECONDS); okHttpClient.connectTimeout(60, TimeUnit.SECONDS); new Retrofit.Builder() .client(okHttpClient.build()) (2认同)

Teo*_*nke 73

这些答案对我来说已经过时了,所以这就是它如何解决的问题.

添加OkHttp,在我的情况下版本是3.3.1:

compile 'com.squareup.okhttp3:okhttp:3.3.1'
Run Code Online (Sandbox Code Playgroud)

然后在构建您的Retrofit之前,执行以下操作:

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();
Run Code Online (Sandbox Code Playgroud)


Sha*_*ami 11

在科特林中:

首先,您应该创建一个OkHttp client并添加到 Retrofit 构建器中

fun create(): Retrofit { 

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


        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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'
Run Code Online (Sandbox Code Playgroud)

  • 请对您的答案进行一些解释。 (4认同)

Mar*_*ouh 5

在 Kotlin 中,您可以retrofit2通过以下方式配置超时

创建OkHttpClient对象(默认值为10秒)

val okHttpClient = OkHttpClient.Builder()
    .connectTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(30, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build()
Run Code Online (Sandbox Code Playgroud)

然后将此对象添加到您的改造构建器中

val retrofit = Retrofit.Builder()
    .addConverterFactory(ScalarsConverterFactory.create())
    .client(okHttpClient)
    .baseUrl(BASE_URL)
    .build()
Run Code Online (Sandbox Code Playgroud)

TimeUnit从此包中导入

import java.util.concurrent.TimeUnit
Run Code Online (Sandbox Code Playgroud)