OkHttp如何配置超時(shí)時(shí)間

小樊
1511
2024-06-18 14:57:01

在OkHttp中,可以通過(guò)設(shè)置Call對(duì)象的timeout()方法來(lái)配置超時(shí)時(shí)間。具體步驟如下:

  1. 創(chuàng)建OkHttpClient對(duì)象:
OkHttpClient client = new OkHttpClient();
  1. 配置超時(shí)時(shí)間:
client = client.newBuilder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .build();

這里connectTimeout()方法用于設(shè)置連接超時(shí)時(shí)間,readTimeout()方法用于設(shè)置讀取超時(shí)時(shí)間,writeTimeout()方法用于設(shè)置寫(xiě)入超時(shí)時(shí)間。這三個(gè)方法均接受兩個(gè)參數(shù),第一個(gè)參數(shù)是時(shí)間值,第二個(gè)參數(shù)是時(shí)間單位。

  1. 使用配置后的OkHttpClient對(duì)象發(fā)送請(qǐng)求:
Request request = new Request.Builder()
        .url("https://www.example.com")
        .build();

Response response = client.newCall(request).execute();

通過(guò)以上步驟,就可以在OkHttp中配置超時(shí)時(shí)間。

0