@@ -37,16 +37,18 @@ public class HttpUtil {
3737 protected static final com .google .common .cache .Cache <String , String > requestCachePool = CacheBuilder .newBuilder ()
3838 .expireAfterWrite (7 , TimeUnit .DAYS )
3939 .build ();
40- private static final OkHttpClient client = new OkHttpClient . Builder ()
41- . cache (new Cache (getCacheFolder () , 50L * 1024L * 1024L )).build ();
40+ private static final File cacheFolder = Util . getCacheFolder ();
41+ private static OkHttpClient client = new OkHttpClient . Builder (). cache (new Cache (cacheFolder , 50L * 1024L * 1024L )).build ();
4242
43+ private static volatile boolean shutdown = false ;
4344
4445 @ Deprecated
4546 public static HttpUtil create () {
4647 return new HttpUtil ();
4748 }
4849
4950 public static Response makeGet (@ NotNull String url ) throws IOException {
51+ checkIfNeedToRecreateClient ();
5052 return client .newCall (new Request .Builder ().get ().url (url ).build ()).execute ();
5153 }
5254
@@ -74,6 +76,7 @@ public static String createGet(@NotNull String url) {
7476
7577 @ Nullable
7678 public static String createGet (@ NotNull String url , boolean flushCache ) {
79+ checkIfNeedToRecreateClient ();
7780 String cache ;
7881 if (!flushCache ) {
7982 cache = requestCachePool .getIfPresent (url );
@@ -99,23 +102,43 @@ public static String createGet(@NotNull String url, boolean flushCache) {
99102
100103 @ NotNull
101104 public static Response makePost (@ NotNull String url , @ NotNull RequestBody body ) throws IOException {
105+ checkIfNeedToRecreateClient ();
102106 return client .newCall (new Request .Builder ().post (body ).url (url ).build ()).execute ();
103107 }
104108
105- @ NotNull
106- private static File getCacheFolder () {
107- File file = new File (Util .getCacheFolder (), "okhttp_tmp" );
108- file .mkdirs ();
109- return file ;
110- }
111109
112110 public static OkHttpClient getClientInstance () {
111+ checkIfNeedToRecreateClient ();
113112 return client ;
114113 }
115114
115+ private static void checkIfNeedToRecreateClient () {
116+ if (shutdown ) {
117+ shutdown = false ;
118+ client = new OkHttpClient .Builder ().cache (new Cache (cacheFolder , 50L * 1024L * 1024L )).build ();
119+ new RuntimeException ("Quickshop HTTPUtil: OkHttpClient is rebuilding, it should not happened outside the testing!" ).printStackTrace ();
120+ }
121+ }
122+
123+ public static void shutdown () {
124+ try {
125+ if (!shutdown ) {
126+ shutdown = true ;
127+ client .dispatcher ().executorService ().shutdown ();
128+ client .connectionPool ().evictAll ();
129+ okhttp3 .Cache cache = client .cache ();
130+ if (cache != null ) {
131+ cache .close ();
132+ }
133+ }
134+ } catch (Throwable ignored ) {
135+ }
136+ }
137+
116138 @ Deprecated
117139 @ NotNull
118140 public OkHttpClient getClient () {
141+ checkIfNeedToRecreateClient ();
119142 return client ;
120143 }
121144}
0 commit comments