参考文章:
WebSocket java客户端请求WSS_Amelia_Liu的博客-CSDN博客_java wss
举例gradle项目,build.gradle中添加:
implementation("org.java-websocket:Java-WebSocket:1.3.0")
java代码,封装客户端:
public abstract class ClientWss extends WebSocketClient {
public ClientWss (URI serverURI) {
super(serverURI);
if(serverURI.toString().contains("wss://"))
trustAllHosts(this);
}
public ClientWss (URI serverURI, Draft draft) {
super(serverURI,draft);
if(serverURI.toString().contains("wss://"))
trustAllHosts(this);
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
static void trustAllHosts(SimpleWss appClient) {
System.out.println("wss start...");
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
@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());
appClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
} catch (Exception e) {
e.printStackTrace();
}
}
}
访问wss:
new ClientWss(new URI(chain)) {
@Override
public void onClose(int arg0, String arg1, boolean arg2) {
// System.out.println(String.format("onClose:【%s】【%s】【%s】", arg0, arg1, arg2));
}
@Override
public void onError(Exception arg0) {
//System.out.println(String.format("onError:%s", arg0));
}
@Override
public void onMessage(String arg0) {
try {
if (StringUtils.isNotBlank(arg0)) {
//业务操作
}
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println(String.format("onMessage:%s", arg0));
this.close();
}
@Override
public void onOpen(ServerHandshake arg0) {
// System.out.println(String.format("onOpen:%s", arg0));
this.send("请求消息");
}
}.connect();
|