最近在做通讯方面的一些东西,移动端与服务器之间的通讯采用HttpUrlConnection以xml文件流的方式进行通讯。xml文件解析后,通常要给对应的数据模型(javabean)赋值,从而进行一些列的验证,入库,日志操作等。
1、通过HttpUrlConnection获取输入流,解码后生成xml文件字符串
2、使用dom4j解析此字符串生成Document对象
3、对Document对象递归遍历收集节点名称和节点值,并根据节点名称拼接set方法,用以和javabean反射后得到的set方法做匹配
具体代码如下:
1、模拟客户端发送xml数据流至服务器 Client.java@H_502_12@
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.net.URLEncoder;
- import java.net.URLDecoder;
- public class Client {
- private static final String POST = "http://localhost:8080/mobileCharge/charge/chargeAction!getMpay.action";
- public static void main(String[] args){
- sendXml();
- }
- public static String createXml() {
- String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<mpay>"
- + "<methodName>getMpay</methodName>" + "<params>" + "<param>"
- + "<type>1</type>" + "<terminalid>91300021</terminalid>"
- + "<money>100.00</money>" + "<csn>02570001</csn>"
- + "<password>1f3259007db02194cd134f18513dd00e</password>"
- + "</param>" + "</params>" + "</mpay>";
- return xml;
- }
- public static void sendXml(){
- try {
- URL url = new URL(POST);
- //根据URL地址打开一个连接
- URLConnection urlConnection = url.openConnection();
- HttpURLConnection httpUrlConnection = (HttpURLConnection)urlConnection;
- //允许输出流
- httpUrlConnection.setDoOutput(true);
- //允许写入流
- httpUrlConnection.setDoInput(true);
- //post方式提交不可以使用缓存
- httpUrlConnection.setUseCaches(false);
- //请求类型
- httpUrlConnection.setRequestProperty("Content-Type","text/html");
- httpUrlConnection.setRequestMethod("POST");
- //设置连接、读取超时
- httpUrlConnection.setConnectTimeout(30000);
- httpUrlConnection.setReadTimeout(30000);
- httpUrlConnection.connect();
- //使用缓冲流将xml字符串发送给服务器
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream()));
- writer.write(URLEncoder.encode(createXml(),"UTF-8"));
- writer.flush();
- writer.close();
- writer = null;
- //关闭连接
- httpUrlConnection.disconnect();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.net.URLDecoder; public class Client { private static final String POST = "http://localhost:8080/mobileCharge/charge/chargeAction!getMpay.action"; public static void main(String[] args){ sendXml(); } public static String createXml() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<mpay>" + "<methodName>getMpay</methodName>" + "<params>" + "<param>" + "<type>1</type>" + "<terminalid>91300021</terminalid>" + "<money>100.00</money>" + "<csn>02570001</csn>" + "<password>1f3259007db02194cd134f18513dd00e</password>" + "</param>" + "</params>" + "</mpay>"; return xml; } public static void sendXml(){ try { URL url = new URL(POST); //根据URL地址打开一个连接 URLConnection urlConnection = url.openConnection(); HttpURLConnection httpUrlConnection = (HttpURLConnection)urlConnection; //允许输出流 httpUrlConnection.setDoOutput(true); //允许写入流 httpUrlConnection.setDoInput(true); //post方式提交不可以使用缓存 httpUrlConnection.setUseCaches(false); //请求类型 httpUrlConnection.setRequestProperty("Content-Type","text/html"); httpUrlConnection.setRequestMethod("POST"); //设置连接、读取超时 httpUrlConnection.setConnectTimeout(30000); httpUrlConnection.setReadTimeout(30000); httpUrlConnection.connect(); //使用缓冲流将xml字符串发送给服务器 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream())); writer.write(URLEncoder.encode(createXml(),"UTF-8")); writer.flush(); writer.close(); writer = null; //关闭连接 httpUrlConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
2、服务端获取到此输入流后转换为字符串,这个很简单,贴出主要代码即可@H_502_12@
- public String getXmlText(){
- //使用的是struts2 ,获取request很方便 O(∩_∩)O~
- HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
- String xmlText=null;
- try{
- //同样使用缓冲流
- BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
- StringBuffer sb = new StringBuffer();
- String lines;
- while((lines = reader.readLine())!=null){
- sb.append(lines);
- }
- //客户端使用了UTF-8编码,这里使用同样使用UTF-8解码
- xmlText = URLDecoder.decode(sb.toString(),"UTF-8");
- reader.close();
- reader = null;
- }catch(Exception e){
- e.printStackTrace();
- }
- return xmlText;
- }
public String getXmlText(){ //使用的是struts2 ,获取request很方便 O(∩_∩)O~ HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST); String xmlText=null; try{ //同样使用缓冲流 BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuffer sb = new StringBuffer(); String lines; while((lines = reader.readLine())!=null){ sb.append(lines); } //客户端使用了UTF-8编码,这里使用同样使用UTF-8解码 xmlText = URLDecoder.decode(sb.toString(),"UTF-8"); reader.close(); reader = null; }catch(Exception e){ e.printStackTrace(); } return xmlText; }
一下就是xmlText与javabean之间的转换了,今天只写了上部分 xml - javabean 改天再写下部分 javabean - xml
3、xmlText - javabean 的转换@H_502_12@
- /**
- * 根据xml文件流对xmlModel赋值
- * @param xmlText
- * @param xmlModel
- * @L_502_8@
- */
- @SuppressWarnings("unchecked")
- public static synchronized Object parseXml4Bean(String xmlText,Object xmlModel){
- try {
- //解析字符串生成docment对象
- Document xmlDoc = DocumentHelper.parseText(xmlText);
- //获取根节点
- Element element = xmlDoc.getRootElement();
- List<Map<String,String>> propsList = new ArrayList<Map<String,String>>();
- //解析xml中的节点名称和节点值,详细见下面parseXml
- propsList = parseXml(element,propsList);
- if(propsList.size()==0){
- return null;
- }
- //获取Method对象数组
- Method[] methods = xmlModel.getClass().getDeclaredMethods();
- for(int i=0;i<propsList.size();i++){
- for(int j=0;j<methods.length;j++){
- Method m = methods[j];
- if(propsList.get(i).containsKey(m.getName())){
- try {
- //执行set方法,将xml中的textNode值赋予Model中
- m.invoke(xmlModel,new Object[]{propsList.get(i).get(m.getName())});
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- } catch (DocumentException e) {
- e.printStackTrace();
- }
- return xmlModel;
- }
/** * 根据xml文件流对xmlModel赋值 * @param xmlText * @param xmlModel * @return */ @SuppressWarnings("unchecked") public static synchronized Object parseXml4Bean(String xmlText,Object xmlModel){ try { //解析字符串生成docment对象 Document xmlDoc = DocumentHelper.parseText(xmlText); //获取根节点 Element element = xmlDoc.getRootElement(); List<Map<String,String>> propsList = new ArrayList<Map<String,String>>(); //解析xml中的节点名称和节点值,详细见下面parseXml propsList = parseXml(element,propsList); if(propsList.size()==0){ return null; } //获取Method对象数组 Method[] methods = xmlModel.getClass().getDeclaredMethods(); for(int i=0;i<propsList.size();i++){ for(int j=0;j<methods.length;j++){ Method m = methods[j]; if(propsList.get(i).containsKey(m.getName())){ try { //执行set方法,将xml中的textNode值赋予Model中 m.invoke(xmlModel,new Object[]{propsList.get(i).get(m.getName())}); } catch (Exception e) { e.printStackTrace(); } } } } } catch (DocumentException e) { e.printStackTrace(); } return xmlModel; }
4、子方法 ,用以解析xml,拼接set方法匹配与Method数组@H_502_12@
- /**
- * 获取xml文件中叶结点名称和节点值
- * @param element
- * @param propsList
- * @return
- */
- @SuppressWarnings("unchecked")
- private static List<Map<String,String>> parseXml(Element element,List<Map<String,String>> propsList){
- if(element.isTextOnly()){
- HashMap<String,String> map = new HashMap<String,String>();
- String key = element.getName();
- key = METHOD_SET+key.substring(0,1).toUpperCase().concat(key.substring(1,key.length()));
- map.put(key,element.getTextTrim());
- propsList.add(map);
- }else{
- List<Element> tmpList = element.elements();
- for(Element e : tmpList){
- parseXml(e,propsList);
- }
- }
- return propsList;
- }
/** * 获取xml文件中叶结点名称和节点值 * @param element * @param propsList * @return */ @SuppressWarnings("unchecked") private static List<Map<String,String>> propsList){ if(element.isTextOnly()){ HashMap<String,String> map = new HashMap<String,String>(); String key = element.getName(); key = METHOD_SET+key.substring(0,1).toUpperCase().concat(key.substring(1,key.length())); map.put(key,element.getTextTrim()); propsList.add(map); }else{ List<Element> tmpList = element.elements(); for(Element e : tmpList){ parseXml(e,propsList); } } return propsList; }
5、java bean@H_502_12@
- package com.eptok.business.charge;
- public class ChargeXmlModel {
- private String methodName;
- private String type;
- private String terminalid;
- private String money;
- private String csn;
- private String password;
- public String getMethodName() {
- return methodName;
- }
- public void setMethodName(String methodName) {
- this.methodName = methodName;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getTerminalid() {
- return terminalid;
- }
- public void setTerminalid(String terminalid) {
- this.terminalid = terminalid;
- }
- public String getMoney() {
- return money;
- }
- public void setMoney(String money) {
- this.money = money;
- }
- public String getCsn() {
- return csn;
- }
- public void setCsn(String csn) {
- this.csn = csn;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
- /////////////////////
-
- package main;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import javax.xml.bind.JAXBContext;
- import javax.xml.bind.JAXBException;
- import javax.xml.bind.Marshaller;
- import javax.xml.bind.Unmarshaller;
- import demo.model.Person;
- public class Main {
- /**
- * @param args
- * @throws JAXBException
- * @throws FileNotFoundException
- */
- public static void main(String[] args) throws JAXBException,FileNotFoundException {
- JAXBContext ctx=JAXBContext.newInstance(Person.class);
- toXML(ctx);
- fromXML(ctx);
- }
- public static void toXML(JAXBContext ctx) throws JAXBException,FileNotFoundException{
- Marshaller ms=ctx.createMarshaller();
- FileOutputStream fo=new FileOutputStream(new File("src/Person.xml"));
- Person p=new Person();
- //"Jack","12";
- p.age="ss";
- ms.marshal(p,fo);
- }
- public static void fromXML(JAXBContext ctx) throws FileNotFoundException,JAXBException{
- FileReader fo=new FileReader(new File("src/Person.xml"));
- Unmarshaller ums= ctx.createUnmarshaller();
- Person p=(Person) ums.unmarshal(fo);
- System.out.println(p.username);
- }
- }
package main; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import demo.model.Person; public class Main { /** * @param args * @throws JAXBException * @throws FileNotFoundException */ public static void main(String[] args) throws JAXBException,FileNotFoundException { JAXBContext ctx=JAXBContext.newInstance(Person.class); toXML(ctx); fromXML(ctx); } public static void toXML(JAXBContext ctx) throws JAXBException,FileNotFoundException{ Marshaller ms=ctx.createMarshaller(); FileOutputStream fo=new FileOutputStream(new File("src/Person.xml")); Person p=new Person(); //"Jack","12"; p.age="ss"; ms.marshal(p,fo); } public static void fromXML(JAXBContext ctx) throws FileNotFoundException,JAXBException{ FileReader fo=new FileReader(new File("src/Person.xml")); Unmarshaller ums= ctx.createUnmarshaller(); Person p=(Person) ums.unmarshal(fo); System.out.println(p.username); } }
- package demo.model;
- import javax.xml.bind.annotation.XmlAttribute;
- import javax.xml.bind.annotation.XmlRootElement;
- @XmlRootElement
- public class Person {
- public Person() {
- super();
- }
- public Person(String username,String age) {
- super();
- this.username = username;
- this.age = age;
- }
- @XmlAttribute
- public String username;
- public String age;
- }