最近的项目在整长连接WebSocket,之前也写过一个感觉没有这个全面。提供个工具类WebSocketHelper和Java-WebSocket-1.3.9.jar包以及一个HttpURLConnectionUtil
1、WebSocketHelper
import android.util.Log;import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;/*** author : jsxin* e-mail : jsxin0816@163.com* time : 2023/07/03* desc : WebSocketHelper工具类*/
public class WebSocketHelper {public static final String TAG = WebSocketHelper.class.getSimpleName();private RobotWebSocket ws_robot;private boolean isRunning;private boolean isInterrupt;public static boolean isOpenOk = false;private WebSocketHelper() {this.isRunning = false;this.isInterrupt = false;}public static WebSocketHelper getInstance() {return SingletonHolder.instance;}public boolean isRunning() {return this.isRunning;}public void ConnectService(final String serive_ip, final String pad_name, final WebSokcetCallback cb) {if (!this.isRunning) {this.isInterrupt = false;Runnable runnable = new Runnable() {public void run() {while(!WebSocketHelper.this.isInterrupt) {WebSocketHelper.this.isRunning = true;if (WebSocketHelper.isOpenOk) {try {Thread.sleep(2000L);} catch (Exception var2) {var2.printStackTrace();}} else {try {String url = "ws://" + serive_ip + "/webSocket/" + 1;System.out.print(url);Log.i(WebSocketHelper.TAG, url);WebSocketHelper.this.ws_robot = WebSocketHelper.this.new RobotWebSocket(new URI(url), new Draft_6455(), cb);WebSocketHelper.this.ws_robot.connectBlocking(10L, TimeUnit.SECONDS);} catch (Exception var4) {Log.e(WebSocketHelper.TAG, var4.getMessage());}try {Thread.sleep(2000L);} catch (Exception var3) {var3.printStackTrace();}}}WebSocketHelper.this.isRunning = false;Log.i(WebSocketHelper.TAG, "robot websocket run over");}};Thread thread = new Thread(runnable);thread.start();}}public int sendMsg(String message) {Log.d(TAG, "message==" + message);synchronized(this.ws_robot) {try {if (this.ws_robot != null) {this.ws_robot.send(message);}} catch (Exception var5) {var5.printStackTrace();isOpenOk = false;return 1;}return 0;}}public void destroy() {try {this.isInterrupt = true;if (this.ws_robot != null) {this.ws_robot.closeBlocking();}} catch (Exception var2) {var2.printStackTrace();}}private class RobotWebSocket extends WebSocketClient {private WebSokcetCallback cb_;RobotWebSocket(URI serverUri, Draft protocolDraft, WebSokcetCallback cb) {super(serverUri);this.cb_ = cb;}public void onOpen(ServerHandshake handshakedata) {Log.i(WebSocketHelper.TAG, "onOpen");WebSocketHelper.isOpenOk = true;if (this.cb_ != null) {this.cb_.onConnect();}}public void onMessage(String message) {Log.d(WebSocketHelper.TAG, "receive: " + message);if (this.cb_ != null) {this.cb_.onMessageData(message);}}public void onClose(int code, String reason, boolean remote) {Log.i(WebSocketHelper.TAG, "Connection close by " + (remote ? "remote peer" : "us") + " at " + new Date(System.currentTimeMillis()));WebSocketHelper.isOpenOk = false;if (this.cb_ != null) {this.cb_.onDisonnect();}}public void onError(Exception ex) {Log.e(WebSocketHelper.TAG, "onError" + ex.getMessage());WebSocketHelper.isOpenOk = false;if (this.cb_ != null) {this.cb_.onDisonnect();}}}public interface WebSokcetCallback {void onConnect();void onDisonnect();void onMessageData(String var1);}private static class SingletonHolder {private static final WebSocketHelper instance = new WebSocketHelper();private SingletonHolder() {}}
}
2、HttpURLConnectionUtil
import android.support.annotation.Nullable;
import android.util.Log;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;/*** author : jsxin* e-mail : jsxin0816@163.com* time : 2023/07/24* desc :*/
public class HttpURLConnectionUtil {public static final String TAG = HttpURLConnectionUtil.class.getSimpleName();public HttpURLConnectionUtil() {}public static String doGet(String httpUrl) {HttpURLConnection connection = null;InputStream is = null;BufferedReader br = null;StringBuffer result = new StringBuffer();try {URL url = new URL(httpUrl);connection = (HttpURLConnection)url.openConnection();connection.setRequestMethod("GET");connection.setReadTimeout(15000);connection.connect();if (connection.getResponseCode() == 200) {is = connection.getInputStream();if (null != is) {br = new BufferedReader(new InputStreamReader(is, "UTF-8"));String temp = null;while(null != (temp = br.readLine())) {result.append(temp);}}}} catch (IOException var19) {var19.printStackTrace();} finally {if (null != br) {try {br.close();} catch (IOException var18) {var18.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException var17) {var17.printStackTrace();}}connection.disconnect();}return result.toString();}public static String doPost(String httpUrl, @Nullable String param) {StringBuffer result = new StringBuffer();HttpURLConnection connection = null;OutputStream os = null;InputStream is = null;BufferedReader br = null;try {URL url = new URL(httpUrl);connection = (HttpURLConnection)url.openConnection();connection.setRequestMethod("POST");connection.setConnectTimeout(15000);connection.setReadTimeout(15000);connection.setUseCaches(false);connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36)");if (null != param && !param.equals("")) {os = connection.getOutputStream();os.write(param.getBytes("UTF-8"));os.flush();}int httpstatus = connection.getResponseCode();Log.i(TAG, "http status :" + httpstatus);if (httpstatus == 200) {is = connection.getInputStream();if (null != is) {br = new BufferedReader(new InputStreamReader(is, "utf-8"));String temp = null;while(null != (temp = br.readLine())) {result.append(temp);result.append("\r\n");}}}} catch (MalformedURLException var30) {var30.printStackTrace();} catch (IOException var31) {var31.printStackTrace();} finally {if (br != null) {try {br.close();} catch (IOException var29) {var29.printStackTrace();}}if (os != null) {try {os.close();} catch (IOException var28) {var28.printStackTrace();}}if (is != null) {try {is.close();} catch (IOException var27) {var27.printStackTrace();}}connection.disconnect();}return result.toString();}
}