HttpURLConnection能构造应用程序和 URL 之间的通信链接,于是解决了我服务器向客户端主动发送消息的难题。 /** * 给PC端发送信息 */ private void sendMessage() { byte[] message = new String("abc123").getBytes();//要发送的消息 OutputStream output = null; try { url = new URL("http://127.0.0.1:8888/server/manage"); connection = (HttpURLConnection)url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "text/html"); connection.setRequestProperty("Content-type", "text/html"); connection.setRequestProperty("Cache-Control","no-cache"); output = connection.getOutputStream();//需要放到setDoOutput方法后面 output.write(message); output.flush(); /*getResponseCode方法很重要,调用它才会将请求发送出去*/ log.info("response code:"+ connection.getResponseCode()); output.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }