踩坑
- 程序中儘可能使用單例OkHttpClient,也就是多個http請求儘可能使用同一個OkHttpClient變量,屢次new OkHttpClient會致使拋出
Too Many ope files
的異常,這個異常是由於多個OkHttpClient鏈接了多個socket致使的,下面是一個使用OkHttpClient的示例
public static OkHttpClient okHttpClient = null;
public static OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).writeTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();
}
return okHttpClient;
}
// 使用的時候調用getOkHttpClient方法獲取同一個OkHttpClient
getOkHttpClient().newCall(req).execute();