ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write("Hello World!".getBytes()); baos.flush();
Socket socket = new Socket("example.com", 80); OutputStream out = socket.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Write data to the ByteArrayOutputStream baos.write("GET / HTTP/1.1\r\n".getBytes()); baos.write("Host: example.com\r\n".getBytes()); // Flush the ByteArrayOutputStream and write to the Socket baos.flush(); out.write(baos.toByteArray());In this example, we create a new Socket and get the OutputStream from the socket. We then create a new ByteArrayOutputStream and write some HTTP headers to it. We call flush() to ensure that the data is written to the byte array and then we write the byte array to the socket. This method is available in the java.io package library.