retrofit设置单个请求的超时

本文系转载,主要代码来源为

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

定义超时的拦截器

/**
 * 自定义的超时拦截器
 */
public class MyTimeoutInterceptor implements Interceptor {
     

    public static final String CONNECT_TIMEOUT = "CONNECT_TIMEOUT";
    public static final String READ_TIMEOUT = "READ_TIMEOUT";
    public static final String WRITE_TIMEOUT = "WRITE_TIMEOUT";

    @Override
    public Response intercept(Chain chain) throws IOException {
     
        int connectTimeout = chain.connectTimeoutMillis();
        int readTimeout = chain.readTimeoutMillis();
        int writeTimeout = chain.writeTimeoutMillis();

        Request request = chain.request();
        String connectNew = request.header(CONNECT_TIMEOUT);
        String readNew = request.header(READ_TIMEOUT);
        String writeNew = request.header(WRITE_TIMEOUT);

        if (!CommonUtil.isEmpty(connectNew)) {
     
            connectTimeout = Integer.parseInt(connectNew);
        }
        if (!CommonUtil.isEmpty(readNew)) {
     
            readTimeout = Integer.parseInt(readNew);
        }
        if (!CommonUtil.isEmpty(writeNew)) {
     
            writeTimeout = Integer.parseInt(writeNew);
        }

        return chain
                .withConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .withReadTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .withWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                .proceed(request);
    }
}

创建retrofit的实例,添加拦截器

private RetrofitSingletonWhjk() {
     
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(10 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(10 * 1000, TimeUnit.MILLISECONDS)
                .addInterceptor(new MyTimeoutInterceptor())
                .addInterceptor(loggingInterceptor)
                .build();
        Gson gson = GsonFactory.getInstance().generateGson();
        String baseUrl = "http://192.168.0.138:8080/test/";
        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

请求时设置头部

/**
     * 上传
     * @param file 文件
     * @param authorization token
     */
    @Multipart
    @Headers({
     "CONNECT_TIMEOUT:600000", "READ_TIMEOUT:600000", "WRITE_TIMEOUT:600000"})
    @POST("upload")
    Call<Result<Object>> upload(@Part MultipartBody.Part file);

你可能感兴趣的:(retrofit,retrofit,单个请求,超时,设置)