Java应用层同步通信HttpURLConnection+Servlet(一)

在多层架构的设计中,实现系统间通信时,我们常常会选择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去传输,注意在客户端和服务器端都要保存对象存根,下一篇文章将给出对象的事例。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值