Skip to content

Commit

Permalink
增加设置网络连接超时方法
Browse files Browse the repository at this point in the history
  • Loading branch information
TheseYears committed Apr 24, 2018
1 parent 5d76408 commit 0547a33
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions CoreLibs/src/main/java/com/corelibs/api/ApiFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.sql.Timestamp;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
Expand Down Expand Up @@ -56,6 +57,8 @@ public class ApiFactory {
private HashMap<String, Retrofit> retrofitMap = new HashMap<>();
private static final boolean IS_ADAPT_GSON_OBJECT_STRING_EXCEPTION = false;

private int timeout = 30;

public static ApiFactory getFactory() {
if (factory == null) {
synchronized (ApiFactory.class) {
Expand Down Expand Up @@ -106,6 +109,14 @@ public <T> T create(String key, Class<T> clz) {
return retrofitMap.get(key).create(clz);
}

/**
* 设置OkHttp连接超时时间,默认30秒,请在{@link #add(String)}或{@link #add(String, String)}之前设置
* @param seconds 秒
*/
public void setTimeout(int seconds) {
timeout = seconds;
}

private void checkRetrofitMap() {
if (retrofitMap.size() <= 0)
throw new IllegalStateException("Please add a Retrofit instance");
Expand Down Expand Up @@ -212,6 +223,9 @@ public Timestamp deserialize(JsonElement json, Type typeOfT,

OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();

clientBuilder.readTimeout(timeout, TimeUnit.SECONDS)
.writeTimeout(timeout, TimeUnit.SECONDS).connectTimeout(timeout, TimeUnit.SECONDS);

if (Configuration.isShowNetworkParams()) {
clientBuilder.addInterceptor(new HttpLoggingInterceptor());
}
Expand Down

0 comments on commit 0547a33

Please sign in to comment.