Home > database >  Non-static method getSocketFactory cannot be referenced from a static context
Non-static method getSocketFactory cannot be referenced from a static context

Time:09-29

I have code that gives the above error as Non-static method getSocketFactory cannot be referenced from a static context. Changing trustAllHost to non-static also did not wroked.

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();
        }
    }

CodePudding user response:

getSocketFactory() is a non-static method. You need an object of SSLContext to call the getSocketFactory() method. As you already created a object of SSLContext
So call

sc.getSocketFactory();

instead of

SSLContext.getSocketFactory();
  • Related