I have tried to use OkHttp3
for connecting to a secure websocket server. When using wss://echo.websocket.org it is working fine, no problem, but when connecting to a production server for an ongoing project I do not properly connect to it. After 30-40 seconds onClosing
is called in WebSocketListener
.
I suspect this has something to with SSL/TLS encryption in wss
. Is there a way to let OkHttpClient accept new certificates?
This is the code I am using now to establish a websocket connection with OkHttp3.
WebSocket webSocket;
OkHttpClient client;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
client = builder.build();
Request request = new Request.Builder()
.url(MainActivity.WS_URL)
.header("Auth-Token","secret-api-token-here")
.build();
Log.i("WebSockets", "Headers: " + request.headers().toString());
webSocket = client.newWebSocket(request, new WebSocketListener() {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("{Auth-Token:secret-api-token-here}");
Log.i("WebSockets", "Connection accepted!");
//webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
Log.i("WebSockets", "Receiving : " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
Log.i("WebSockets", "Receiving bytes : " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
Log.i("WebSockets", "Closing : " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
Log.i("WebSockets", "Error : " + t.getMessage());
}});
}
I used OkHttp3
websocket to connect with a server over encrypted connection wss
and I face the same problem. Which later turned out that the server was closing the connection after certain period of time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With