无法从静态上下文中引用非静态方法 getSocketFactory

Non-static method getSocketFactory cannot be referenced from a static context

我的代码给出了上述错误,因为无法从静态上下文中引用非静态方法 getSocketFactory。将 trustAllHost 更改为非静态也没有发生变化。

WebSocketClient(URI serverUri, String topic, Map<String, String> headers) {
        super(serverUri, headers);
        if (serverUri.toString().contains("wss://"))
            trustAllHosts(this);
        this.topic = topic;
    }

    static void trustAllHosts(MCPWebSocketClient appClient) {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub

            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub

            }
        }};

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory factory = SSLContext.getSocketFactory(); //this line
            appClient.setSocket(factory.createSocket());
            appClient.connectBlocking();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

getSocketFactory() 是一个非静态方法。您需要一个 SSLContext 对象来调用 getSocketFactory() 方法。因为您已经创建了 SSLContext
的对象 所以调用

sc.getSocketFactory();

而不是

SSLContext.getSocketFactory();