Java HTTPS: / / websocket cannot connect to Android
•
Android
I have connected the socket http: / / (with port) the URL is complete and works normally, but I have connected HTTPS: / / (without port) which does not work in Java websocket
I use gradle to rely on 'org. Java websocket: Java websocket: 1.3.0'
WebSocketClient mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.e(TAG, "Websocket: " + "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void connect() {
super.connect();
//Log.e(TAG, "Websocket: " + "connect");
SharedPreference.storeValue(mContext, SharedPreference.WEB_SOCKET_STATUS, SharedPreference.WEB_SOCKET_CONNECT);
}
}
resolvent:
I found a solution!) If you want to use WSS: / /, set setwebsocketfactory
public void connect() {
final String url = "wss://echo.websocket.org";
URI uri=null;
try{
uri = new URI(url);
}
catch (URISyntaxException e)
{
Log.e(TAG, e.getMessage());
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.e(TAG,"Connected!");
}
@Override
public void onMessage(String message) {
Log.e(TAG,"Message: "+message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
Log.e(TAG,"Disconnected!");
}
@Override
public void one rror(Exception ex) {
Log.e(TAG,"Error: "+ex.getMessage());
}
};
if (url.indexOf("wss") == 0) {
try {
SSLContext sslContext = SSLContext.getDefault();
mWebSocketClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
} catch (Exception e) {
e.printStackTrace();
}
}
mWebSocketClient.connect();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码