千羽12138 2023-02-08 15:38 采纳率: 33.3%
浏览 15

okHttp耗时问题

下载图片场景
okhttp设置了读超时事件,但是从日志来看好像没有生效,而且正好是默认的10s,都消耗在了response.body().bytes()。


    private static final ConnectionPool mConnectionPool = new ConnectionPool(connectionPoolSize, 30, TimeUnit.MINUTES);

    public static OkHttpClient getHttpClient(int timeout, EventListener listener) {
        return new OkHttpClient.Builder()
                .followRedirects(false)
                .retryOnConnectionFailure(false)
                .connectTimeout(2000, TimeUnit.MILLISECONDS) //连接超时
                .readTimeout(timeout, TimeUnit.MILLISECONDS) //读取超时
                //ThreadPoolExecutor(0, 2147483647, 60L, TimeUnit.SECONDS, new SynchronousQueue(), Util.threadFactory("OkHttp ConnectionPool", true));
                .connectionPool(mConnectionPool)
                .eventListener(listener)
                .build();
    }

    public static byte[] downloadFileWithOKHttpClient(String url, int timeoutSecond) throws IOException {
        OKHttpClientEventListener listener = new OKHttpClientEventListener();
        OkHttpClient client = getHttpClient(timeoutSecond * 1000, listener);
        Request request = new Request.Builder()
                //访问路径
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                long l = response.body().contentLength();
                byte[] bytes = response.body().bytes();
                return bytes;
            } else {
                throw new RuntimeException();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        downloadFileWithOKHttpClient("",5);
    }

log:

14:33:52.471 callStart
14:33:52.472 dnsStart
14:33:52.472 dnsEnd
14:33:52.472 connectStart
14:33:52.504 secureConnectStart
14:33:52.664 secureConnectEnd
14:33:52.665 connectEnd
14:33:52.665 connectionAcquired
14:33:52.665 requestHeadersStart
14:33:52.665 requestHeadersEnd
14:33:52.665 responseHeadersStart
14:33:52.828 responseHeadersEnd
14:33:52.828 responseBodyStart
14:34:02.162 responseBodyEnd
14:34:02.162 connectionReleased
14:34:02.162 callEnd

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-02-08 18:03
    关注
    评论

报告相同问题?

问题事件

  • 创建了问题 2月8日

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计