使用URL传送对象到另一平台

业务场景需要把平台A的数据传送到另一平台B,然后在B端保存数据,两边的数据表是一样的,数据类型有几个不同,考虑了使用httpclient、socket和webservice等几种解决方案后,最后选用了使用URL的ObjectStream来传送对象,代码:

import java.io.InputStream;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.HttpURLConnection;

/**
 * 数据推送工具类
 * 2011-5-24
 */
public class DataPushUtil {

	/**
	 * 数据推送处理
	 * @param goal_url
	 * @param obj
	 * @throws Exception 
	 */
	@SuppressWarnings("unused")
	public static void dataPush(String goal_url, Object obj) throws Exception{
		String push_url = "http://" + Constants.CBS_URL + "/" + goal_url;
	    
	    URL url = new URL(push_url);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setDoOutput(true);
		urlConn.setDoInput(true);
		urlConn.setUseCaches(false);
		urlConn.setRequestProperty("Content-type","application/x-java-serialized-object");
		urlConn.setRequestMethod("POST");
		urlConn.connect();
		OutputStream outStrm = urlConn.getOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(outStrm);

		oos.writeObject(obj);
		oos.flush();
		oos.close();
		@SuppressWarnings("unused")
		InputStream inStrm = urlConn.getInputStream();
	}
	
}

 DataPushUtil是对象的推送工具类,调用方法很简单,只需要两个参数,goal_url是要推送到的url,obj是要传送的对象。

接收的处理代码:

	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		InputStream in = request.getInputStream();
		ObjectInputStream ois = new ObjectInputStream(in);
		try{
			Object push_info = ois.readObject();
			
		}catch(Exception e){
			e.printStackTrace();
		}
 在doPose方法里使用ObjectInputStream把传送的ObjectStream解析成Object,要传送的对象必须实现Serializable接口。

你可能感兴趣的:(java,.net,webservice,socket)