无法从静态上下文中引用非静态方法 getSocketFactory [重复]
Posted
技术标签:
【中文标题】无法从静态上下文中引用非静态方法 getSocketFactory [重复]【英文标题】:Non-static method getSocketFactory cannot be referenced from a static context [duplicate] 【发布时间】:2021-09-29 08:33:46 【问题描述】:我的代码给出了上述错误,因为无法从静态上下文引用非静态方法 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();
【问题讨论】:
【参考方案1】:getSocketFactory() 是一个非静态方法。您需要一个 SSLContext 对象来调用 getSocketFactory() 方法。因为您已经创建了 SSLContext 的对象 所以调用
sc.getSocketFactory();
而不是
SSLContext.getSocketFactory();
【讨论】:
以上是关于无法从静态上下文中引用非静态方法 getSocketFactory [重复]的主要内容,如果未能解决你的问题,请参考以下文章
无法从静态上下文中引用非静态方法 getSocketFactory [重复]