日记: 使用OkHttp请求WebSocket.报错onFailure

在使用okhttp请求WebSocket报错执行了WebSocketListener中onFailure方法, 这个问题让我找了2个小时所以记录下来 ┌────────────────────────────────────── │ RealWebSocket.failWebSocket (RealWebSocket.java:546) │ WebsocketWorker$MyWebSocketListener.onFailure (WebsocketWorker.java:117) ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ │ onFailure:Throwable:Conversion: , Response:null └──────────────────────────────────────

这里是WebSocketListener监听回调使用打印库为com.orhanobut:logger

public static class MyWebSocketListener extends WebSocketListener {
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            Logger.i("onOpen:%", response);
        }
        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
            Logger.i("onMessage:%", bytes);
        }
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            Logger.i("onMessage:%", text);
        }
        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            Logger.i("onClosed:code:%d, reason:%s", code, reason);
        }
        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            Logger.i("onClosing:code:%d, reason:%s", code, reason);
        }
        @Override
        public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
            super.onFailure(webSocket, t, response);
117           Logger.i("onFailure:Throwable:%s, Response:%s", t.getMessage(), response); //报错位置
        }
    }

原因:websocket监听回调执行onOpen方法, 由于格式化缺少%s所以报错,但是没有抛出错误而是执行onFailure回调了 okhttp中的RealWebSocket.java

 // Process all web socket messages.
        try {
          listener.onOpen(RealWebSocket.this, response);
          String name = "OkHttp WebSocket " + request.url().redact();
          initReaderAndWriter(name, pingIntervalMillis, streams);
          streamAllocation.connection().socket().setSoTimeout(0);
          loopReader();
        } catch (Exception e) {
          failWebSocket(e, null);
        }

找问题心得

  1. 使用测试用例很重要
  2. 写测试代码不要使用原代码可能存在debug
  3. 遇见问题看文档,看代码,网上找

okhttp这样设计合理吗? 请评论

转载于:https://my.oschina.net/xtdhwl/blog/1587440

你可能感兴趣的:(日记: 使用OkHttp请求WebSocket.报错onFailure)