在多层架构的设计中,实现系统间通信时,我们常常会选择webservice,这是一种面向服务编程的思想,是给异构系统提供同步调用服务的。如果是采用纯java开发平台,并且对扩展性、持续集成性要求不高时,实际上我们可以采用另外一种比较简洁的通信方式来实现系统间通信,那就是使用HttpURLConnection和servlet,我做了一个简单的demo:
服务端采用servlet实现(接收并返回字节流),下面为doPost方法的主体代码:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get input stream from client InputStream inStream = req.getInputStream(); /* Read input stream */ DataInputStream dataIS = new DataInputStream(inStream); BufferedInputStream bIS = new BufferedInputStream(dataIS); byte[] b = new byte[10]; bIS.read(b); System.out.println(new String(b)); /* Response to client */ OutputStream os = resp.getOutputStream(); DataOutputStream dataOS = new DataOutputStream(os); dataOS.write("response".getBytes()); dataOS.flush(); dataOS.close(); }
客户端为普通java应用程序,使用HttpURLConnection类发送http请求,代码如下:
public static void main(String[] args) throws Exception { //Set up a url URL url = new URL("http://localhost:8088/Servlet/httpConnectionServletTest"); //Generate url connection URLConnection urlConn = url.openConnection(); //Switch to http url connection HttpURLConnection httpUrlConn = (HttpURLConnection) urlConn; /* Output into http connection or not. * If send get request, the parameter is false; * If send post request, the parameter is true; */ httpUrlConn.setDoOutput(true); //Input into http connection or not. httpUrlConn.setDoInput(true); //User cache or not httpUrlConn.setUseCaches(false); //Request context type is url encode httpUrlConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); //Set request method httpUrlConn.setRequestMethod("POST"); //Get tcp connection httpUrlConn.connect(); //get output stream object OutputStream outputStream = httpUrlConn.getOutputStream(); DataOutputStream dataOS = new DataOutputStream(outputStream); //Flush the memory buffer and put the bytes into output stream dataOS.write("request".getBytes()); dataOS.flush(); dataOS.close(); //Invoke method getInputStream() to send data to server InputStream inStream = httpUrlConn.getInputStream(); /* Get response from server * You can invoke available method to get the length of stream */ byte[] inB = new byte[inStream.available()]; inStream.read(inB); System.out.println((new String(inB)).toString()); }
以上代码只实现了传输普通字节流,当然,也可以像RMI那样去传输对象字节流,无非就是让对象实现Serializable接口,然后序列化为Object Stream去传输,注意在客户端和服务器端都要保存对象存根,下一篇文章将给出对象的事例。