[英]Unable to connect websocket with wss in android
我正在嘗試使用 org.java_websocket.client.WebSocketClient API 在 android 中連接安全的 websocket 連接 wss://,但無法連接 https。 但是它與 ws:// 一起工作正常。這是我的代碼。
private void connect(String websocketEndPointUrl) throws Exception {
URI uri;
try {
websocketEndPointUrl="wss://echo.websocket.org:443";
Log.i(TAG, " WSURL: " + websocketEndPointUrl);
uri = new URI(websocketEndPointUrl);
} catch (URISyntaxException e) {
Log.e(TAG, e.getMessage());
return;
}
mWebSocketClient = new WebSocketClient(uri,new Draft_17()) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
}
@Override
public void onMessage(String s) {
//final String message =s;
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
我正在使用在線測試 websocket url: ws://echo.websocket.org (port 80) // 使用 wss://echo.websocket.org (port 443) 根據我的觀察,不需要證書在我的代碼中。 任何人都可以建議我是什么原因以及如何解決這個問題。
找到解決辦法。 我不知道為什么這不是文檔的一部分。 您只需要在 WebSocketClient 初始化之后和.connect .connect()
方法之前設置setWebSocketFactory
mWebSocketClient = new WebSocketClient(uri,new Draft_17())
{
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
}
@Override
public void onMessage(String s) {
//final String message =s;
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
if (websocketEndPointUrl.indexOf("wss") == 0)
{
try {
SSLContext sslContext = SSLContext.getDefault();
mWebSocketClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
mWebSocketClient.connect();
就我而言,當 websocket connect()
時,我需要做兩件事來修復“未找到認證路徑的信任錨”錯誤:
HttpsURLConnection
至少成功請求該特定 wss 主機(但以https://
形式)一次。setWebSocketFactory()
接受的答案中所述執行setWebSocketFactory()
。 這個額外的方法(加上new Draft_17()
)只出現在庫版本org.java-websocket:Java-WebSocket:1.3.0
,而不是1.4.0
。 請注意,不要像這個答案那樣使用allowAllSSL()
測試,這會影響上述兩件事不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.