java 序列化的作用
public class Test { public static String requestUrl = "http://localhost/SpringMvc/test.do"; public static void main(String[] args) { TestVo test = new TestVo(); test.setName("baichuanyu"); test.setAge(20); HttpURLConnection httpUrlConn = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; ObjectOutputStream oos = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(requestUrl); httpUrlConn = (HttpURLConnection)url.openConnection(); // 设置content_type=SERIALIZED_OBJECT // 如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException httpUrlConn.setRequestProperty("Content-Type","application/x-java-serialized-object"); httpUrlConn.setConnectTimeout(10000); httpUrlConn.setReadTimeout(10000); // 设置是否向httpUrlConn输出,因为是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false httpUrlConn.setDoOutput(true); // 设置是否从httpUrlConn读入,默认情况下是true httpUrlConn.setDoInput(true); // 不使用缓存 httpUrlConn.setUseCaches(false); // 设置请求方式,默认是GET httpUrlConn.setRequestMethod("POST"); httpUrlConn.connect(); if (test != null) { // 此处getOutputStream会隐含的进行connect,即:如同调用上面的connect()方法, // 所以在开发中不调用上述的connect()也可以,不过建议最好显式调用 // write object(impl Serializable) using ObjectOutputStream oos = new ObjectOutputStream(httpUrlConn.getOutputStream()); oos.writeObject(test); oos.flush(); // outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络, // 而是存在于内存缓冲区中,待outputStream流关闭时,根据输入的内容生成http正文。所以这里的close是必须的 oos.close(); } // 将返回的输入流转换成字符串 // 无论是post还是get,http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去 inputStream = httpUrlConn.getInputStream();//注意,实际发送请求的代码段就在这里 inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } } catch (Exception e) { System.out.println(e); } finally { try { bufferedReader.close(); inputStreamReader.close(); inputStream.close(); oos.close(); if (httpUrlConn != null) { httpUrlConn.disconnect(); } } catch (Exception e) { } } } }
网络传输:通过推送改变网站中比如map中存储的对象
@RequestMapping(value = "/test", method = RequestMethod.POST) public void javaSerialize(HttpServletResponse response,HttpServletRequest request) { try { ObjectInputStream ois = new ObjectInputStream(request.getInputStream()); TestVo user = (TestVo) ois.readObject(); System.out.println(user.getName()+":"+user.getAge()); map.put("user", user); PrintWriter w = response.getWriter(); w.print("已收到"); w.flush(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }