okhttp 有websocket吗
时间: 2023-10-18 07:13:41 浏览: 84
是的,OkHttp支持WebSocket。从OkHttp版本3.5开始,它就内置了WebSocket API,可以用来进行WebSocket通信。您可以使用OkHttp的WebSocket API来建立WebSocket连接、发送消息和接收消息。以下是一个使用OkHttp WebSocket的示例代码:
```java
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("ws://echo.websocket.org")
.build();
WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
// WebSocket连接成功
webSocket.send("Hello, WebSocket!");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
// 收到消息
System.out.println("Received message: " + text);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
// WebSocket关闭中
System.out.println("WebSocket closing: " + reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
// WebSocket已关闭
System.out.println("WebSocket closed: " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// WebSocket失败
System.out.println("WebSocket failure: " + t.getMessage());
}
});
```
在这个示例代码中,我们使用OkHttp建立了一个WebSocket连接到"ws://echo.websocket.org"地址,然后发送了一条消息"Hello, WebSocket!"。当WebSocket收到消息时,会通过onMessage()方法回调通知我们。当WebSocket关闭时,会通过onClosing()和onClosed()方法回调通知我们。当WebSocket失败时,会通过onFailure()方法回调通知我们。
阅读全文