在项目中,不同的两个服务器如果存在相互传输数据的时候,如果一般用HTTP-URL传输的话,要考虑很多问题,而且URL的get方法不能传输过多的数据。
出于安全和业务方面的考虑,服务器之间、客户端和服务器之间使用IO流来传输数据不失为一种很好的解决方案。也不用过多考虑出现乱码的问题等。而在绝大多数时候,我们涉及的是较大规模的数据交换和敏感信息加密等,使用带参数的格式显然不能满足我们的要求,这就涉及了不同Web主机上的Servlet之间数据对象的相互传输的问题。基于JSON 的数据传输技术(发送并接收)1 String jsonStr="{'user':'user1','password':'16468498498'}"; 2 String ecod=null; 3 //加密 4 try { 5 ecod = Des3.encode(jsonStr); 6 } catch (Exception e1) { 7 e1.printStackTrace(); 8 } 9 10 try {11 12 13 URL url = new URL("http://www.testService.com/data.action"); 14 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 15 urlConn.setDoOutput(true);16 urlConn.setDoInput(true);17 urlConn.setUseCaches(false); 18 urlConn.setRequestProperty("Content-type","application/x-java-serialized-object"); 19 urlConn.setRequestMethod("POST"); 20 urlConn.connect(); 21 OutputStream outStrm = urlConn.getOutputStream(); 22 outStrm.write(ecod.getBytes()); 23 outStrm.flush();24 outStrm.close();25 }26 27 //接收到的返回数据 已加密(使用特定的密钥)28 InputStream i = urlConn.getInputStream(); 29 BufferedReader in = new BufferedReader(new InputStreamReader(i));30 StringBuffer buffer = new StringBuffer();31 String line = "";32 while ((line = in.readLine()) != null){33 buffer.append(line);34 }35 line = buffer.toString();36 System.out.println(line);
基于JSON 的数据传输技术(处理并返回)
1 public void doPost(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 4 5 request.setCharacterEncoding("UTF-8"); 6 String dcod = null; 7 InputStream i = request.getInputStream(); 8 BufferedReader in = new BufferedReader(new InputStreamReader(i)); 9 StringBuffer buffer = new StringBuffer();10 String line = "";11 while ((line = in.readLine()) != null){12 buffer.append(line);13 }14 dcod = buffer.toString();15 String s = null;16 if(dcod!=null){17 18 try {19 //解密 20 s = Des3.decode(dcod);21 } catch (Exception e) {22 23 e.printStackTrace();24 }25 }26 27 ActionMap amp= (ActionMap) JsonUtil.getDtoFromJsonObjStr(s,ActionMap.class);//将json数据转换成对象28 /***这里是业务逻辑处理***/29 OutputStream ooo = response.getOutputStream();30 31 //返回数据32 ooo.write(result.getBytes());33 ooo.flush();34 ooo.close();35 36 }