java socket调用接口_java调用websocket接口

项目中需要调用第三方语音电话接口,代码如下:

1.pom.xml引入websocket依赖

org.java-websocket

Java-WebSocket

1.3.8

2.YiWeiDialUtil.java

package com.yudu.sms.util;

import com.alibaba.fastjson.JSONObject;

import org.java_websocket.WebSocket;

import org.java_websocket.client.WebSocketClient;

import org.java_websocket.handshake.ServerHandshake;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.net.URI;

import java.net.URISyntaxException;

public class YiWeiDialUtil {

private static final Logger logger = LoggerFactory.getLogger(YiWeiDialUtil.class);

public static void dial(String ws, String phone, String recordName) {

try {

URI uri = new URI(ws);

WebSocketClient client = new WebSocketClient(uri) {

@Override

public void onOpen(ServerHandshake serverHandshake) { }

@Override

public void onMessage(String s) {

logger.info("返回的数据:" + s);

JSONObject jo = JSONObject.parseObject(s);

String dynamicdata = jo.getString("dynamicdata");

if (dynamicdata != null) {

JSONObject jo_dynamicdata = JSONObject.parseObject(dynamicdata);

String realtimestate = jo_dynamicdata.getString("realtimestate");

if (realtimestate.equals("outconnected")) {

send("{\"command\":\"closeheadsettochannel\"}");

String recordMp3 = System.getProperty("user.dir") + "\\src\\main\\resources\\" + recordName + ".mp3";

String record = "{\"command\":\"PlayStartRecord\",\"arguments\":{\"content\":\"" + recordMp3 + "\"}}";

send(record);

}

}

}

@Override

public void onClose(int i, String s, boolean b) { }

@Override

public void onError(Exception e) {

logger.error(e.getMessage());

}

};

//建立连接

client.connect();

while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {

logger.info("连接中...");

}

String dial = "{\"command\":\"Dial\",\"arguments\":{\"phone\":\"" + phone + "\"}}";

client.send(dial);

} catch (URISyntaxException e) {

logger.info(e.getMessage());

}

}

}

···

你可能感兴趣的:(java,socket调用接口)