【问题标题】:OkHttp Websockets - Add a body when connecting to websocketOkHttp Websockets - 连接到 websocket 时添加一个主体
【发布时间】:2020-02-11 08:01:14
【问题描述】:

我正在使用 okHttp websocket 库,并且成功连接到我的 websocket 服务器,但目前我只能在连接时获取连接 ID。我想在正文中发送一些额外的信息,但我不知道如何使用 okHttp 添加它

Request request = new Request.Builder()
                .url("wss://mywebsocketurl.com")
                .build();

我试过了

RequestBody requestBody = new FormBody.Builder()
.add("camera_id", "e9502c54-927c-4639-a94f-8d03149c9c62")
.build();


Request request = new Request.Builder()
                .url("wss://mywebsocketurl.com")
                .method("POST", requestBody)
                .build();


Request request = new Request.Builder()
                .url("wss://mywebsocketurl.com")
                .post(requestBody)
                .build();

但它总是返回

java.lang.IllegalArgumentException: method GET must not have a request body.

【问题讨论】:

    标签: android websocket okhttp


    【解决方案1】:

    我知道现在回答为时已晚。 无论如何,该网址应该只是 GET。所以我建立了连接并在 onOpen 回调函数上发送了正文。它奏效了。

    private fun initializeSocket(url: String) {
        val request: Request = Request.Builder().url(url).build()
        val listener = WebSocketListener()
        webSocket = client!!.newWebSocket(request, listener)
        client?.dispatcher()?.executorService()?.shutdown()
    }
    
    private class WebSocketListener : WebSocketListener() {
        override fun onOpen(webSocket: WebSocket, response: Response?) {
            val content = "{\n" +
                    "  \"messageType\": \"INIT_CONNECTION\"\n" +
                    "}"
            webSocket.send(content)
        }
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 2019-05-01
      • 2022-09-24
      • 2019-03-27
      • 1970-01-01
      • 2018-02-19
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多