Java应用层同步通信HttpURLConnection+Servlet(一)
程序员文章站
2022-07-13 13:42:22
...
在多层架构的设计中,实现系统间通信时,我们常常会选择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去传输,注意在客户端和服务器端都要保存对象存根,下一篇文章将给出对象的事例。
推荐阅读
-
Java中线程同步锁和互斥锁有啥区别?看完你还是一脸懵逼?
-
Java并发之传统线程同步通信技术代码详解
-
Java多线程-同步:synchronized 和线程通信:生产者消费者模式
-
java-Synchronized 一种同步锁的使用
-
死磕 java同步系列之ReentrantLock源码解析(一)——公平锁、非公平锁
-
JAVA多线程的一个复习例子(取款同步)(希望大家不要看源代码,看题目自己写出实现)
-
Java队列同步器(AQS)到底是怎么一回事
-
Java应用层同步通信HttpURLConnection+Servlet(一)
-
Java 多线程同步问题的探究(二、给我一把锁,我能创造一个规矩)
-
关于Java里面多线程同步的一些知识