Android OKHttp3 超时设置和异常捕获

 private void getService() {
        OkHttpClient client = new OkHttpClient();

        //请求超时设置
        client.newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();

        Request.Builder request = new Request.Builder().url("URL");
        Call call = client.newCall(request.build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (e instanceof SocketTimeoutException) {
                    //判断超时异常
                }
                if (e instanceof ConnectException) {
                    ////判断连接异常,

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

你可能感兴趣的:(Android)