如何创建简单的okhttp3 websocket连接? [英] How to create simple okhttp3 websocket connection?

查看:1000
本文介绍了如何创建简单的okhttp3 websocket连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我演示一个示例,该示例如何使用okhttp3 okhttp-ws库建立具有特定Authorization标头的wss://地址的连接吗?

Can someone please show me an example on how to establish the connection to the wss:// address with specific Authorization header, using okhttp3 okhttp-ws library?

我所拥有的只是WS服务器的URL和授权字符串令牌.

All I have is the url of WS server and Authorization string token.

稍后,我必须能够向该连接发送请求,侦听来自WS服务器的即将到来的数据,然后关闭连接.我在这个新的WS世界中遇到了困难,始终只使用REST(也使用okhttp3)

Later, I must be able to send request to that connection, listen to upcoming data from WS server and than close connection. I have a difficulties with this new to me WS world, always been working only with REST (with okhttp3 too)

推荐答案

因此,此示例通常是您所需要的大多数

So generally this sample is most of what you need

https: //github.com/square/okhttp/blob/d854e6d5ad93da4da9b5d5818ee752477e501b18/samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java

但是您将进行两项更改

  1. 在网址中使用wss代替ws
  2. 调用request.addHeader添加令牌

  1. Use wss instead of ws in your URL
  2. Call request.addHeader to add your token

request.addHeader("Authorization","Bearer" +令牌)

request.addHeader("Authorization", "Bearer " + token)

这篇关于如何创建简单的okhttp3 websocket连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆