OkHttp设置连接超时时间

时间:2021-10-14 00:55:29


private OkManager() {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
.build();
client.writeTimeoutMillis();
gson = new Gson();
handler = new Handler(Looper.getMainLooper());

builder = new Request.Builder();

// builder.header("Accept","application/json");
builder.header("Accept-Encoding", "application/json");
builder.header("Content-Type", "");


}

处理异常

private void netWordFaild(Call call, IOException e) {
if (e instanceof SocketTimeoutException) {//判断超时异常
ToastUtils.showLong("Socket网络请求超时");
return;
}
if (e instanceof ConnectException) {//判断连接异常,我这里是报Failed to connect to 10.7.5.144
ToastUtils.showLong("网络请求超时");
return;
}
ToastUtils.showLong("网络错误");


Log.e(TAG, "网络错误" + e.toString());
}